Returning a file to View/Download in ASP.NET MVC

前端 未结 9 1557
刺人心
刺人心 2020-11-21 22:41

I\'m encountering a problem sending files stored in a database back to the user in ASP.NET MVC. What I want is a view listing two links, one to view the file and let the mim

相关标签:
9条回答
  • 2020-11-21 23:06

    I had trouble with the accepted answer due to no type hinting on the "document" variable: var document = ... So I'm posting what worked for me as an alternative in case anybody else is having trouble.

    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);
    }
    
    0 讨论(0)
  • 2020-11-21 23:06

    FileVirtualPath --> Research\Global Office Review.pdf

    public virtual ActionResult GetFile()
    {
        return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
    }
    
    0 讨论(0)
  • 2020-11-21 23:09

    To view file (txt for example):

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

    To download file (txt for example):

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

    note: to download file we should pass fileDownloadName argument

    0 讨论(0)
提交回复
热议问题