Ask Question

Download a file in JavaScript via Ajax

In the past I've executed my file download requests with provided an a element with the download attribute, or opening the link to the file in a new browser tab. In those cases the Web Application was secured via a session cookie so I had no problems with this approach.

But in my current project it's a bit different, because the API is secured with a Json Web Token which is not stored as a Cookie or in the localStorage. Therefore I would need to call the download url via Ajax (we use Axios for this in our case) so I can provide the JWT. The Ajax call returns me the File as a Blob, but now I'm not sure how I can prompt the Browser to download the file onto the file system of the user.

JavaScriptaxiosajax

1222 views

Authorยดs Dominik Sumer image

Dominik Sumer

Last edited on

1 Answer available

Best answer

Ok I found out how I can do it. With the Blob which is returned from the Axios call I can convert it to an object url, create an a element with it and simulate a click event, so that the Browser prompts the file download.

If you don't want to implement this by your own, there is the js-file-download library: GitHub
It also checks if the browser supports the download attribute and opens the link in a new tab as fallback.

PS:
Don't forget to set the responseType of your Ajax request to blob. This will ensure that the file is being downloaded correctly, else it will probably be appear as corrupted.

๐Ÿ‘
1