首页 > 解决方案 > 从控制器发送文件以查看

问题描述

我正在尝试将文件从 MVC 5 控制器发送到 angularjs 客户端。我需要在响应中指定文件名。

[HttpGet]
public ActionResult DownloadAttachment([FromUri] long NoteId)
{
    var attachment = db.tcp_tahGeneral_downloadNotesAttachment_API(NoteId).First();
    var path = attachment.AttachmentLocation;

    if (File.Exists(path))
    {
        FileStream stream = new FileStream(path, FileMode.Open);
        byte[] file = new byte[stream.Length];
        stream.Read(file, 0, file.Length);

        return new FileContentResult(file, attachment.AttachmentFileType);
    }
    return null;
}

这会发送文件,但不允许我指定新文件名。

标签: c#.netangularjsasp.net-mvc

解决方案


FileContentResult中有一个FileDownloadName设置文件名的属性,你可以试试下面的 return 语句。

return new FileContentResult(file, attachment.AttachmentFileType) 
           { 
              FileDownloadName = "myfilename.myext"
           };

推荐阅读