首页 文章

将文件返回到ASP.NET MVC中的查看/下载

提问于
浏览
258

我在ASP.NET MVC中将存储在数据库中的文件发送回用户时遇到问题 . 我想要的是一个列出两个链接的视图,一个用于查看文件,让发送给浏览器的mimetype确定应该如何处理,另一个用于强制下载 .

如果我选择查看名为 SomeRandomFile.bak 的文件并且浏览器没有相关程序来打开这种类型的文件,那么我没有问题,它默认为下载行为 . 但是,如果我选择查看名为 SomeRandomFile.pdfSomeRandomFile.jpg 的文件,我希望文件只是打开 . 但是我也希望将下载链接保留在一边,这样无论文件类型如何,我都可以强制下载提示 . 这有意义吗?

我已经尝试了 FileStreamResult 并且它适用于大多数文件,默认情况下's constructor doesn' t接受文件名,因此根据url(根据内容类型不知道要提供的扩展名)为未知文件分配文件名 . 如果我通过指定文件名强制它,我将失去浏览器直接打开文件的能力,我得到一个下载提示 . 有人遇到过这种情况么 .

这些是我迄今为止尝试过的例子 .

//Gives me a download prompt.
return File(document.Data, document.ContentType, document.Name);
//Opens if it is a known extension type, downloads otherwise (download has bogus name and missing extension)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);
//Gives me a download prompt (lose the ability to open by default if known type)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name};

有什么建议?

8 回答

  • 10

    FileVirtualPath - > Research \ Global Office Review.pdf

    public virtual ActionResult GetFile()
    {
        return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
    }
    
  • 1

    我相信这个答案更清晰,(基于https://stackoverflow.com/a/3007668/550975

    public ActionResult GetAttachment(long id)
        {
            FileAttachment attachment;
            using (var db = new TheContext())
            {
                attachment = db.FileAttachments.FirstOrDefault(x => x.Id == id);
            }
    
            return File(attachment.FileData, "application/force-download", Path.GetFileName(attachment.FileName));
        }
    
  • 385

    下面的代码对我来说是从API服务获取pdf文件并将其响应给浏览器 - 希望它有所帮助;

    public async Task<FileResult> PrintPdfStatements(string fileName)
        {
             var fileContent = await GetFileStreamAsync(fileName);
             var fileContentBytes = ((MemoryStream)fileContent).ToArray();
             return File(fileContentBytes, System.Net.Mime.MediaTypeNames.Application.Pdf);
        }
    
  • 105

    view 文件(例如txt):

    return File("~/TextFileInRootDir.txt", MediaTypeNames.Text.Plain);
    

    download 文件(例如txt):

    return File("~/TextFileInRootDir.txt", MediaTypeNames.Text.Plain, "TextFile.txt");
    

    注意:要下载文件我们应该传递 fileDownloadName 参数

  • 8

    由于"document"变量没有类型暗示,我对接受的答案有困难: var document = ... 所以我发布了对我有用的东西,以防其他人遇到麻烦 .

    public ActionResult DownloadFile()
    {
        string filename = "File.pdf";
        string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Path/To/File/" + filename;
        byte[] filedata = System.IO.File.ReadAllBytes(filepath);
        string contentType = MimeMapping.GetMimeMapping(filepath);
    
        var cd = new System.Net.Mime.ContentDisposition
        {
            FileName = filename,
            Inline = true,
        };
    
        Response.AppendHeader("Content-Disposition", cd.ToString());
    
        return File(filedata, contentType);
    }
    
  • 1

    Darin Dimitrov's answer是对的 . 只是一个补充:

    如果您的响应已包含"Content-Disposition"标头, Response.AppendHeader("Content-Disposition", cd.ToString()); 可能会导致浏览器无法呈现文件 . 在这种情况下,您可能想要使用:

    Response.Headers.Add("Content-Disposition", cd.ToString());
    
  • -1
    public ActionResult Download()
    {
        var document = ...
        var cd = new System.Net.Mime.ContentDisposition
        {
            // for example foo.bak
            FileName = document.FileName, 
    
            // always prompt the user for downloading, set to true if you want 
            // the browser to try to show the file inline
            Inline = false, 
        };
        Response.AppendHeader("Content-Disposition", cd.ToString());
        return File(document.Data, document.ContentType);
    }
    

    注意:上面的示例代码无法正确说明文件名中的国际字符 . 有关标准化,请参阅RFC6266 . 我相信最新版本的ASP.Net MVC的 File() 方法和 ContentDispositionHeaderValue 类正确地解释了这一点 . - 奥斯卡2016-02-25

  • 0

    Another easy way is

    public ActionResult GetLoadingLogo()
    {
      if (1 == 1)
      {
        return new FilePathResult(Server.MapPath("~/Content/Images/ajaxLoader_dhanlaxmi.gif"), "image/gif");
      }
      else
      {
        return new FilePathResult(Server.MapPath("~/Content/Images/add-icon.png"), "image/png");
      }
    }
    

相关问题