Can suggest: Download file from site html
Arijit singh mp3 free download | Activeperl download windows 10 |
Free screencast download | Minecraft console greek mythology texture pack download for pc |
Franz ferdinand take me out mp3 download free | Download adobe illustrator middle east version |
Spectrum reading grade 2 pdf free download | Download post malone torrent |
Kindle antivirus free download full version | The reading lesson book free download |
Shing Lyu
When building websites or web apps, creating a “Download as file” link is quite useful. For example if you want to allow user to export some data as JSON, CSV or plain text files so they can open them in external programs or load them back later. Usually this requires a web server to format the file and serve it. But actually you can export arbitrary JavaScript variable to file entirely on the client side. I have implemented that function in one of my project, MozApoy, and here I’ll explain how I did that.
First, we create a link in HTML
The attribute will be the filename for your file. It will look like this:
Notice that we keep the attribute blank. Traditionally we fill this attribute with a server-generated file path, but this time we’ll assign it dynamically generate the link using JavaScript.
Then, if we want to export the content of the variable as a text file, we can use this JavaScript code:
The magic happens on the third line, the API takes a Blob and returns an URL to access it. The URL lives as long as the document in the window on which it was created. Notice that you can assign the type of the data in the constructor. If you assign the correct format, the browser can better handle the file. Other commonly seen formats include and . For example, if we name the file as and give it , Firefox will recognize it as “CSV document” and suggest you open it with LibreOffice Calc.
And in the last line we assign the url to the element’s 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.)
Everytime you call , a new object URL will be created, which will use up the memory if you call it many times. So if you don’t need the old URL anymore, you should call the API to free them.
This is a simple trick to let your user download files without setting up any server. If you want to see it in action, you can check out this CodePen.
-