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

前端 未结 1 1931
别那么骄傲
别那么骄傲 2021-01-05 04:52

I\'ve been able to write JavaScript to cause the browser to download a file from a remote server using code like this:

var iframe = document.createElement(\"         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 05:28

    In some newer browsers you can use the new HTML5 download attribute on 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 could look into the HTML5 FileSystem API, but this API is not currently supported in most of the major browsers. It might not be of much use to you except for that it might provide you with another way to store the files locally if you would be OK with that. But it doesn't store the files on the users locally accessible file system, you would have to develop your own browser based interface for your users to interact with the files. Downloading the files from the HTML5 file system to the users local file system would in any case again be done using the new download attribute on an a tag, which would then refer to a location in the HTML5 file system instead of referring to an online location.

    To do this with an iframe element you would have to somehow set the Content-Disposition request header on the iframe to inline; filename="filename.txt" using client side JavaScript, I don't think it is possible to do this, most likely because of security issues. If you really don't have any other option, you could kill the download speed performance by sending the string to the server using AJAX and then downloading it from there again with the right request headers set.

    0 讨论(0)
提交回复
热议问题