1

Get Web-API method to download zip file

This code is not working

Please help me out on this.

public HttpResponseMessage SampleDownload()
            {
                try {
                    HttpResponseMessage result = null;
                    var path = @"D:\sample\sample.zip";
                    var filename = "sample.zip";
                    if (File.Exists(path))
                    {
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        var stream = new FileStream(path, FileMode.Open);
                        result.Content = new StreamContent(stream);
                        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        result.Content.Headers.ContentDisposition.FileName = filename;
                    }
                    return result;
    }
aydinugur
  • 1,208
  • 2
  • 14
  • 21
trinetra
  • 21
  • 1
  • 6
  • 1
    Hi, perhaps include what error or output you are receiving, to give some insight into why the code is failing? :) – flauntster Nov 09 '17 at 07:23
  • Thanks Flauntster , I got the code working.but with a different approach. Reference: " https://stackoverflow.com/questions/41383338/how-to-download-a-zipfile-from-a-dotnet-core-webapi ". Did some modification for client-side. – trinetra Nov 09 '17 at 09:32
  • @trinetra: Post what you did to solve the issue as answer and then accept it when you can. That way this question doesn't remain perpetually in the "unanswered" status. – Chris Pratt Nov 09 '17 at 14:18
  • @ChrisPratt Thanks for reminding. Will do it tomorrow – trinetra Nov 09 '17 at 15:35

1 Answers1

1

C# Web API Code:

public IActionResult GetZipFile(string filename)
{
    // It can be zip file or pdf but we need to change contentType respectively
    const string contentType ="application/zip";
    HttpContext.Response.ContentType = contentType;
    var result = new FileContentResult(System.IO.File.ReadAllBytes(@"{path_to_files}\file.zip"), contentType)
    {
         // It can be zip file or pdf but we need to change the extension respectively
        FileDownloadName = $"{filename}.zip"
    };

    return result;
}

Angular Code:

Requirement: FileSaver ( Install file saver package)

import * as FileSaver from 'file-saver';

 this.http.get(url,{ responseType: ResponseContentType.Blob }).subscribe((response)=>{
             var blob = new Blob([response['_body']], {type: "application/zip"});
              FileSaver.saveAs(blob,dlData.file_name);
        }).catch((error) => {
           // Error code
        });

Reference url : How to download a ZipFile from a dotnet core webapi?

trinetra
  • 21
  • 1
  • 6