How to get a web browser to download a file that is stored in a JavaScript string?

I was able to write JavaScript to force the browser to download the file from a remote server using the following code:

var iframe = document.createElement("iframe"); iframe.style.display = "none"; iframe.src = "filename.zip" document.body.appendChild(iframe); 

Which works great. However, now I have a different situation when the contents of the file are stored in a string in my JavaScript on the browser side, and I need to cause the download of this file. I tried replacing the third line above, where "myFileContents" is the line containing the actual bytes of the file:

 iframe.src = "data:application/octet-stream;base64," + Base64.encode(myFileContents); 

This loads the file, but the file name is lost. In Chrome, the file name is just β€œloading”. I also read that in some versions of the browser there are restrictions on the file size.

Is there any way to achieve this? Using jQuery will be fine. The solution should support any type of file - zip, pdf, csv, png, jpg, xls, etc.

+7
source share
1 answer

In several new browsers, you can use the new HTML5 download attribute in the a tag to achieve this:

 var a = document.createElement('a'); a.download = "filename.txt"; a.href = "data:application/octet-stream;base64," + Base64.encode(myFileContents); a.click(); 

For a future solution, you can explore the HTML5 FileSystem API, but this API is not currently supported in most major browsers . This may not be very useful for you, except that it may provide you with another way to store files locally if you are okay with this. But it does not store files on a locally accessible file system of users; you will have to develop your own browser-based interface so that your users can interact with files. In any case, downloading files from the HTML5 file system to the local file system of users will again be performed using the new tag upload attribute a , which will then refer to the location in the HTML5 file system and not to the Internet.

To do this with an iframe element, you need to somehow set the Content-Disposition request header on the iframe to inline; filename="filename.txt" inline; filename="filename.txt" using client-side JavaScript, I don’t think it can be done, most likely due to security issues. If you really have no other option, you can kill the download speed by sending a string to the server using AJAX and then downloading it again using the correct set of request headers.

+10
source

All Articles