[英]How to use local drive path in ASP.NET MVC4
我已經將文件保存在本地驅動器中,現在卡住了,將其取回屏幕。
方案-
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.cardFilePath
是D:\\FunRanger2\\FunRangerPhotos\\Desert.png
試圖以圖像形式獲得它
<img src="@Model.cardFilePath" height="300" width="300" />
我所得到的只是那里沒有圖像。
如何在查看頁上獲取此圖像?
您需要將該圖片相對於您的網站放置,以便將其投放。 例如,如果將圖像放置在網站的根目錄中,則路徑將僅是圖像名稱。 如果將其放在名為images
的文件夾中,則類似於/images/{image_name}
。
考慮一下瀏覽器在做什么。 它正在嘗試訪問客戶端計算機上D:\\FunRanger2\\FunRangerPhotos
的文件。
您必須使用File
結果創建一個動作:返回以下文件而不是返回視圖:
return File("FileName", "img/png");
此重載有兩個參數。 第一個是文件的路徑。 第二個是文件的MIME類型,它與文件類型/擴展名有關,例如, 在此處 ,您可以輕松找到這種類型的lis。
然后,您只需要將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" />
您可以將文件夾映射為IIS中的虛擬目錄。 首先,將文件存儲在D驅動器中。 如下圖所示,將D驅動器映像的位置映射為虛擬目錄(只需在IIS中右鍵單擊網站節點,然后選擇“添加虛擬目錄”)。
這樣可以使用相對路徑訪問所有D驅動器位置。
將其添加為虛擬目錄后,就可以在代碼中按以下方式使用它。
<img src='~/Images/.....your image name...' />
您可以將圖像讀取為字節數組並將其返回到視圖
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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.