C# 图像未从路径加载

C# 图像未从路径加载,c#,asp.net,sql-server,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Sql Server,Asp.net Mvc,Asp.net Mvc 4,未从asp.net中的给定路径加载映像 下面是一个场景。我已使用asp.net将图像上载到文件夹中,并将其路径插入SQL server数据库,但当我尝试从asp应用程序中的路径获取图像时,“路径正确”,但图像加载失败。没有错误 以下是上传数据的代码 if (FileUpload1.HasFile && TextArea1.Value != null) { string fileName = Path.GetFileName(FileUpload1.Post

未从asp.net中的给定路径加载映像 下面是一个场景。我已使用asp.net将图像上载到文件夹中,并将其路径插入SQL server数据库,但当我尝试从asp应用程序中的路径获取图像时,“路径正确”,但图像加载失败。没有错误

以下是上传数据的代码

if (FileUpload1.HasFile && TextArea1.Value != null)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string path = Server.MapPath("/admin/images/" +fileName);
        FileUpload1.PostedFile.SaveAs(Server.MapPath("/admin/images/" + fileName));
        //Response.Write("<script>alert('" + path + "');</script>");
        string ta1 = TextArea1.Value;
        string sql = "UPDATE homep SET img = '" + path + "', description= '" + ta1.Replace("'", "''") + "' WHERE id = 1;";
        cmd = new SqlCommand(sql, con);
        if (cmd.ExecuteNonQuery() > 0)
        {
            Response.Write("<script>alert('Updation Success ..!');</script>");
        }
    }
if(FileUpload1.HasFile&&TextArea1.Value!=null)
{
string fileName=Path.GetFileName(FileUpload1.PostedFile.fileName);
字符串路径=Server.MapPath(“/admin/images/”+文件名);
FileUpload1.PostedFile.SaveAs(Server.MapPath(“/admin/images/”+fileName));
//写(“警报(“+path+”);”;
字符串ta1=TextArea1.Value;
string sql=“UPDATE homep SET img=”+path+”,description=”+ta1.Replace(“”,““”)+”,其中id=1;“;
cmd=新的SqlCommand(sql,con);
if(cmd.ExecuteNonQuery()>0)
{
响应。写入(“警报('updatesuccess..!);”;
}
}
以下是获取数据的代码

 dr.Read();
   Response.Write("<img src='"+dr["img"].ToString()+"' class='img-responsive'/>");
   dr.Close();
dr.Read();
回答。写(“”);
Close博士();

您在服务器硬盘上为浏览器提供了一条物理路径,客户端的浏览器无法打开该路径。您应该构建一个为图像服务的actionmethod,并从您的图像在src=”“中提供该actionmethod的url

例如:

Response.Write("<img src='/Serveimage/?path="+dr["img"].ToString()+"' class='img-responsive'/>");
像这样使用~:

Server.MapPath("~/admin/images/" +fileName)

感谢您提供的解决方案,但我正在使用数据库检索路径。所以我可以把这个路径放在这个方法中,我是从数据库中得到的。在图像的src中,仍然像在初始代码中那样指定路径。此路径作为url参数(请参见?path=)传递给我建议的actionmethod。此方法将从硬盘读取文件并将其提供给浏览器。请注意,出于安全原因,您应该对代码进行一些更改。例如,ServeImage方法只是盲目地将您请求的任何文件服务器上。另外,将整个路径放在html中可能不是一个好主意,而是图像的id,并让ServeImage方法从数据库检索路径。感谢解决方案,我已经这样做了,但仍然无法工作。物理路径出现错误,我给出了物理路径,但根据上面发布的答案,虚拟路径是必需的。我只给出了路径,并删除了服务器。MapPathno不删除服务器。MapPath(此处的图像路径)。。。。。。。然后图像必须位于项目文件文件夹中
Server.MapPath("~/admin/images/" +fileName)