Reputation: 21
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;
}
Upvotes: 1
Views: 3418
Reputation: 21
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?
Upvotes: 1