use*_*444 18 asp.net-mvc download hyperlink filepath
我有带有对象表的网页.
我的一个对象属性是文件路径,该文件位于同一网络中.我想要做的是将此文件路径包装在链接下(例如下载),在用户单击此链接后,该文件将下载到用户计算机中.
在我的桌子里面:
@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>
Run Code Online (Sandbox Code Playgroud)
我创建了这个下载链接:
<th width ="150"><p><b><a href="default.asp" target="_blank">Download</a></b></p></th>
Run Code Online (Sandbox Code Playgroud)
我想要这个下载链接来包装我file path
,然后点击链接将倾向于我的控制器:
public FileResult Download(string file)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(file);
}
Run Code Online (Sandbox Code Playgroud)
我需要添加到我的代码中才能实现这一点?
meh*_*cek 31
从您的操作中返回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;
}
Run Code Online (Sandbox Code Playgroud)
和下载链接,
<a href="controllerName/Download?file=@item.fileName" target="_blank">Download</a>
Run Code Online (Sandbox Code Playgroud)
此链接将使用参数fileName向您的下载操作发出get请求.
编辑:对于找不到的文件,你可以,
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26140 次 |
最近记录: |