
Stan Georgian 180 Followers Full-Stack Web Developer. Refresh the page, check Medium ’s site status, or find something interesting to read. So if you don’t need the old URL anymore, you should call the revokeObjectURL() API to free them. How to Download Files With JavaScript by Stan Georgian ITNEXT Write Sign up Sign In 500 Apologies, but something went wrong on our end. For example, if we name the file as *.csv and give it type: 'text/csv', Firefox will recognize it as “CSV document” and suggest you open it with LibreOffice Calc.Īnd in the last line we assign the url to the element’s href attribute, so when the user clicks on the link, the browser will initiate an download action (or other default action for the specific file type.)Įverytime you call createObjectURL(), a new object URL will be created, which will use up the memory if you call it many times. Other commonly seen formats include application/json and text/csv. If you assign the correct format, the browser can better handle the file. So my folder is something like : rootFolder -JS file -HTML file -download file (sample. Notice that you can assign the type of the data in the new Blob() constructor. I want to be able to download a given file when pressing a button.The file will be provided via an API call.For now, I will have it in my local storage.

The URL lives as long as the document in the window on which it was created.

The magic happens on the third line, the () API takes a Blob and returns an URL to access it. Var url = (data) ĭocument.getElementById('download_link').href = url
