如何在ASP.NET MVC4中使用本地驱动器路径

时间:2014-01-24 13:40:33

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我已将File保存在本地驱动器中,现在仍然无法将其恢复到屏幕。

方案 -

 public ActionResult Upload(HttpPostedFileBase file, CardModel card) {
        CardTable cardtable = new CardTable();
        if (file != null && file.ContentLength > 0) {
            // TODO: storing uploaded files to the App_Data folder on the server. 
            // Adjust this location to fit your requirements
            var drivepath = "D:\\FunRanger2\\FunRangerPhotos";
            var filepath = Path.Combine(drivepath, Path.GetFileName(file.FileName));
            file.SaveAs(filepath);
            cardtable.CardFileName = file.FileName;
            cardtable.CardFilePath = filepath;
            cardtable.CardDate = DateTime.Now;
            cardtable.CardTitle = card.cardTitle;
            cardtable.CardHashCode = card.cardHashCode == null ? "" : card.cardHashCode;
            db.CardTables.InsertOnSubmit(cardtable);
            db.SubmitChanges();
        }

作为示例,我将文件Desert.png保存到此目录位置。

因此,此路径更新了数据库CardFilePath列 -

D:\FunRanger2\FunRangerPhotos\Desert.png

在观看方面 -

我检查此路径是否来自模型值 -

@Model.cardFilePathD:\FunRanger2\FunRangerPhotos\Desert.png

尝试将其置于图片中

 <img src="@Model.cardFilePath" height="300" width="300"  />

我得到的只是没有图像。

如何在viewpage上获取此图片?

4 个答案:

答案 0 :(得分:0)

您需要将该图片相对于您的网站放置,以便提供服务。例如,如果将图像放在网站的根目录中,则路径将只是图像名称。如果将其放在名为images的文件夹中,则类似于/images/{image_name}

想想浏览器在做什么。它正在尝试访问 客户端计算机上D:\FunRanger2\FunRangerPhotos处的文件。

答案 1 :(得分:0)

您必须使用File结果创建操作:而不是返回视图,返回如下文件:

return File("FileName", "img/png");

此重载有两个参数。第一个是文件的路径。 seocond one是您文件的MIME类型,与文件类型/扩展名相关,您可以轻松找到此类型的lis,例如here

然后,您只需将src属性指向此属性,例如使用Url.Action()

<img src="@Url.Action(...)" height="300" width="300"  />

您宁愿在此操作中使用id,而不是使用服务器路径。例如:

public Image(int id)
{
    // get the filePath using the id:
    string filePath = ...;
    // get the mime type from the file extension
    string mimeType;
    return File(filePath, mimeType);
}

在剃须刀中使用它:

<img src="@Url.Action("Image", "ControllerName", new { id = ...})" 
    height="300" width="300"  />

答案 2 :(得分:0)

您可以将文件夹映射为IIS中的虚拟目录。首先将文件存储在D Drive中。将D Drive Images的位置映射为虚拟目录(只需右键单击IIS中的网站节点,然后选择添加虚拟目录),如下所示。

这将使用相对路径访问所有D Drive位置。

enter image description here

将其添加为虚拟目录后,您可以在代码中将其用作以下内容。

<img src='~/Images/.....your image name...' />

答案 3 :(得分:0)

您可以将图像读取为bytearray并将其返回到视图

public ActionResult Picture()
        {
            Byte[] Picture;

            var filePath = "D:\FunRanger2\FunRangerPhotos\Desert.png";
            if (System.IO.File.Exists(filePath))
            {
                Picture = System.IO.File.ReadAllBytes(filePath);
            }

            return File(Picture, "image/png");
        }