无法使用创建的路径显示图像Server.MapPath

时间:2018-01-15 07:24:00

标签: c# asp.net-mvc

我正在尝试在项目根目录下的文件夹中显示网页上的图像。我存储在数据库中的路径如下:

  

d:\项目\ OnlineStore \ OnlineStore \ OnlineStore \内容\上传\ IMAGES \捆绑\ 706976d31e274e7ab36986b9bec2f0f9 - 对象   image.jpg的

生成此路径的代码如下:

var path = Path.Combine(Server.MapPath("~/Content/Uploads/Images/Bundles"), fileId);
photo.SaveAs(path);

使用此路径无法显示图像。有效的路径如下:

  

\内容\上传\ IMAGES \捆绑\ 706976d31e274e7ab36986b9bec2f0f9 - 对象   image.jpg的

如何解决此问题?我正在考虑使用第一个路径将图像文件保存到文件夹并保存数据库中的第二个路径。但这似乎不是正确的做法。

2 个答案:

答案 0 :(得分:1)

1。仅在数据库中存储FileName检查this

  string fileName = System.IO.Path.GetFileName(file.FileName);

 //store fileName in your ImageName column of Image your Image table
 //Note: generate unique filename using `Guid` or `PrimaryKey` to overcome    
 //same file name issue.

2。使用@Url.Content在视图中显示图片。

<img  src="@Url.Content("~")/Content/Uploads/Images/Bundles/@Model.ImageName"/>

Reference

答案 1 :(得分:0)

在控制器中:

public ActionResult UserRegister(Register Register)
    {
        try
        {
            DbConnection dbHandle = new DbConnection();
            dbHandle.Connection();

             using (SqlCommand UserRegistercmd = new SqlCommand("USPUserRegistration", dbHandle.con))
                {
                    DateTime dob = Convert.ToDateTime(Register.dateOfBirth);
                    string Random = System.DateTime.Now.ToString("ddMMyyhhmmss");
                    Register.UserPhoto = "../Images/" + Random + Register.userImg.FileName;
                    Register.userImg.SaveAs(Server.MapPath("../Images/") + Random + Register.userImg.FileName);
                    UserRegistercmd.CommandType = CommandType.StoredProcedure;

                    dbHandle.con.Open();
                    UserRegistercmd.ExecuteNonQuery();
                    dbHandle.con.Close();
                    ViewBag.error = "Company Registration Sucess";

                    Mail.SendMail(Register.email,"Your User Name and Password ","User Name :"+Register.username+"Paassword :"+Register.password);
                }
        }
        catch (Exception e)
        {
            ViewBag.error = "Error!!";
            ExceptionLog.Log(e, Request.UserHostAddress);
            return RedirectToAction("Error_View", "CompanyRegister");
        }
        finally
        {
            Dispose();
        }
        return RedirectToAction();
    }

在cshtml中使用@ Url.Content:

  <img src="@Url.Content(@Model.UserPhoto)" alt="There is no Image" style="height:150px;width:150px" onclick="ChangeImg()" />
相关问题