Spawn Download from the client side Script

In a client-side application, in a browser written in Javascript, you can use local storage to save state. If the user requires the ability to retrieve their data from the client application, one of them sends content to the server and returns the server back with the correct content type and other headers to start the download operation.

Is there a way to start such a load operation using the purely client side of the script without sending content to the server and repeating it back?

+4
source share
2 answers

, : Blob, createObjectURL() anchor.

JSFiddle , Chrome Internet Explorer, Chrome ( "" Windows, .) http://jsfiddle.net/fa9y6/9/

Blob :

var blob = new Blob([ $('#documentContent').val() ], { type: mimeType });

Internet Explorer:

if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename); 
}

Chrome ( Firefox) anchor click() it:

var a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.click();
if (a.remove) a.remove();

, dragstart:

if (window.chrome) {
     document.body.addEventListener('dragstart', function(e) {
         // Some use a class, here. My sample only has one save button.
         if (e.target.id == 'downloadButton') {      
             var blob = new Blob([ $('#documentContent').val() ], { type: mimeType });
             e.dataTransfer.setData('DownloadURL', [mimeType, $('#fileName').val(), window.URL.createObjectURL(blob)].join(':'));
         }
     });
}

( .)

+4

FileSaver.js, saveAs:

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

IE10 +.

+3

Source: https://habr.com/ru/post/1548324/


All Articles