Asp.net-Mvc
從我網頁內的連結下載文件
我有帶有對象表的網頁。
我的對象屬性之一是文件路徑,該文件位於同一網路中。我想要做的是將此文件路徑包裝在連結下(例如下載),在使用者點擊此連結後,文件將下載到使用者機器中。
所以在我的桌子裡面:
@foreach (var item in Model) { <tr> <th width ="150"><p><b><a href="default.asp" target="_blank">Download</a></b></p></th> <td width="1000">@item.fileName</td> <td width="50">@item.fileSize</td> <td bgcolor="#cccccc">@item.date<td> </tr> } </table>我創建了這個下載連結:
<th width ="150"><p><b><a href="default.asp" target="_blank">Download</a></b></p></th>我想要這個下載連結來包裝我的
file path並點擊連結將傾向於我的控制器:public FileResult Download(string file) { byte[] fileBytes = System.IO.File.ReadAllBytes(file); }我需要在我的程式碼中添加什麼才能實現這一點?
從您的操作中返回 FileContentResult。
public FileResult Download(string file) { byte[] fileBytes = System.IO.File.ReadAllBytes(file); var response = new FileContentResult(fileBytes, "application/octet-stream"); response.FileDownloadName = "loremIpsum.pdf"; return response; }還有下載連結,
<a href="controllerName/Download?file=@item.fileName" target="_blank">Download</a>此連結將使用參數 fileName 向您的下載操作發出獲取請求。
編輯:對於未找到的文件,您可以,
public ActionResult Download(string file) { if (!System.IO.File.Exists(file)) { return HttpNotFound(); } var fileBytes = System.IO.File.ReadAllBytes(file); var response = new FileContentResult(fileBytes, "application/octet-stream") { FileDownloadName = "loremIpsum.pdf" }; return response; }