显示相对图像URL的图像不起作用

时间:2017-04-24 16:50:08

标签: asp.net-mvc database

我已经采取了将文件上传到文件系统并将文件路径保存在数据库中的路线。

我已经通过

成功将图像文件上传到(“〜/ Content / images”+ fileName)
string path = System.IO.Path.Combine(Server.MapPath("~/Content/images" + 
fileName));

我已成功将文件路径保存到数据库。

auction.ImageURL = path;

但是图像没有渲染,经过检查,图像源网址反映了图像的绝对路径

C:\Users\cmazzochi81\Documents\Visual Studio\2015\Projects\MyAuctionApp\Content\images

发生了什么事?

控制器 -

[Authorize]
[HttpPost]
    public ActionResult Create(Models.Auction auction, HttpPostedFileBase file)
    {

        if (ModelState.IsValid)
        {
            if (file != null)
            {
                string fileName = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(
                                       Server.MapPath("~/Content/images" + fileName));

                // file is uploaded
                file.SaveAs(path);
                var db = new AuctionsDataContext();
                auction.ImageURL = path;
                db.Auctions.Add(auction);
                db.SaveChanges();
                return RedirectToAction("Index");

            }

        }
        return Create();  
    }

模型

[DataType(DataType.ImageUrl)]
[Display(Name = "image URL")]
public string ImageURL { get; set; }

视图 -

<img src="@auction.ImageURL" title="@auction.Title" />

1 个答案:

答案 0 :(得分:1)

Server.MapPath返回提供的虚拟路径的物理目录。如果您正在查找可在img src属性中使用的文件夹的虚拟路径,则您将要使用VirtualPathUtility.ToAbsolute

由于听起来您想要保存文件(因此需要物理路径)并返回指向文件的链接(因此需要虚拟路径),因此您需要同时使用这两种文件。

    if (ModelState.IsValid)
    {
        if (file != null)
        {
            string fileName = System.IO.Path.GetFileName(file.FileName);
            string savePath = System.IO.Path.Combine(Server.MapPath("~/Content/images"), fileName);
            string url =  System.IO.Path.Combine(VirtualPathUtility.ToAbsolute("~/Content/images"), fileName);

            // file is uploaded
            file.SaveAs(savePath);
            var db = new AuctionsDataContext();
            auction.ImageURL = url;
            db.Auctions.Add(auction);
            db.SaveChanges();
            return RedirectToAction("Index");

        }
相关问题