加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 从我的网页链接下载文件

发布时间:2020-12-15 19:16:35 所属栏目:asp.Net 来源:网络整理
导读:我有页面与对象表. 我的一个对象属性是文件路径,这个文件位于同一个网络中.我想做的是将此文件路径包装在链接下(例如下载),用户点击此链接后,该文件将下载到用户机器中. 所以在我的桌子里面 @foreach (var item in Model) { tr th width ="150"pba href="def
我有页面与对象表.

我的一个对象属性是文件路径,这个文件位于同一个网络中.我想做的是将此文件路径包装在链接下(例如下载),用户点击此链接后,该文件将下载到用户机器中.

所以在我的桌子里面

@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>

我想要这个下载链接包装我的文件路径,点击链接将倾向于我的控制器:

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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读