How to download a ZipFile from a dotnet core webapi?

后端 未结 1 650
故里飘歌
故里飘歌 2021-01-14 01:49

I am trying to download a zip file from a dotnet core web api action, but I can\'t make it work. I tried calling the action via POSTMAN and my Aurelia Http Fetch Client.

1条回答
  •  天涯浪人
    2021-01-14 02:39

    To put a long story short, the example below illustrates how to easily serve both a PDF as well as a ZIP through a dotnet-core api:

    /// 
    /// Serves a file as PDF.
    /// 
    [HttpGet, Route("{filename}/pdf", Name = "GetPdfFile")]
    public IActionResult GetPdfFile(string filename)
    {
        const string contentType = "application/pdf";
        HttpContext.Response.ContentType = contentType;
        var result = new FileContentResult(System.IO.File.ReadAllBytes(@"{path_to_files}\file.pdf"), contentType)
        {
            FileDownloadName = $"{filename}.pdf"
        };
    
        return result;
    }
    
    /// 
    /// Serves a file as ZIP.
    /// 
    [HttpGet, Route("{filename}/zip", Name = "GetZipFile")]
    public IActionResult GetZipFile(string filename)
    {
        const string contentType ="application/zip";
        HttpContext.Response.ContentType = contentType;
        var result = new FileContentResult(System.IO.File.ReadAllBytes(@"{path_to_files}\file.zip"), contentType)
        {
            FileDownloadName = $"{filename}.zip"
        };
    
        return result;
    }
    

    This sample just works™

    Notice in this case there is only one main difference between the two actions (besied the source file name, of course): the contentType that is returned.

    The example above uses 'application/zip', as you've mentioned yourself, but it might just be required to serve a different mimetype (like 'application/octet*').

    This leads to the speculation that either the zipfile cannot be read properly or that your webserver configuration might not be configured properly for serving .zip files.

    The latter may differ based on whether you're running IIS Express, IIS, kestrel etc. But to put this to the test, you could try adding a zipfile to your ~/wwwroot folder, making sure you have enabled serving static files in your Status.cs, to see if you can download the file directly.

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