Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Download File in ASP.NET Core API from Axios Request

Good day guys,

I'm trying to download file from ASP.NET Core Web API from Axios Request.

Here's my sample API method. (Code based from this stackoverflow question)

[HttpPost("download")]
public async Task<IActionResult> DownloadFile(){
    ...
    return File(new MemoryStream(mypdfbyte), "application/octet-stream", "myfile.pdf");
}

Here's my sample axios request.

axios.post(`api/products/download`).then(response=>{
    console.log(response.data)
}).catch(error=>{ console.log(error) })

But I'm only receiving this. No download file appears.

enter image description here

I hope you can help me download a file from my controller api.

like image 739
AppleCiderYummy Avatar asked Mar 13 '19 09:03

AppleCiderYummy


People also ask

How do I download from .NET core API?

ASP.NET 5 WEB API & Angular 12 You may create an anchor tag in your front-end app programmatically and set the href property to an object URL created from the Blob by the method below. Now clicking on the anchor will download the file. You can set a file name by setting the 'download' attribute to the anchor as well.

How do I download a file from API?

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.


1 Answers

First of all, DownloadFile should be HttpGet instead of HttpPost. Then your axios request should look like

axios({
  url: 'http://localhost:5000/api/products/download',
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'file.pdf');
  document.body.appendChild(link);
  link.click();
});
like image 130
kriss Avatar answered Oct 11 '22 02:10

kriss