Download data url file

前端 未结 9 1448
猫巷女王i
猫巷女王i 2020-11-22 09:34

I\'m playing with the idea of making a completely JavaScript-based zip/unzip utility that anyone can access from a browser. They can just drag their zip directly into the br

相关标签:
9条回答
  • 2020-11-22 09:57

    Here is a pure JavaScript solution I tested working in Firefox and Chrome but not in Internet Explorer:

    function downloadDataUrlFromJavascript(filename, dataUrl) {
    
        // Construct the 'a' element
        var link = document.createElement("a");
        link.download = filename;
        link.target = "_blank";
    
        // Construct the URI
        link.href = dataUrl;
        document.body.appendChild(link);
        link.click();
    
        // Cleanup the DOM
        document.body.removeChild(link);
        delete link;
    }
    

    Cross-browser solutions found up until now:

    downloadify -> Requires Flash

    databounce -> Tested in IE 10 and 11, and doesn't work for me. Requires a servlet and some customization. (Incorrectly detects navigator. I had to set IE in compatibility mode to test, default charset in servlet, JavaScript options object with correct servlet path for absolute paths...) For non-IE browsers, it opens the file in the same window.

    download.js -> http://danml.com/download.html Another library similar but not tested. Claims to be pure JavaScript, not requiring servlet nor Flash, but doesn't work on IE <= 9.

    0 讨论(0)
  • 2020-11-22 09:57

    For anyone having issues in IE:

    Please upvote the answer here by Yetti: saving canvas locally in IE

    dataURItoBlob = function(dataURI) {
        var binary = atob(dataURI.split(',')[1]);
        var array = [];
        for(var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], {type: 'image/png'});
    }
    
    var blob = dataURItoBlob(uri);
    window.navigator.msSaveOrOpenBlob(blob, "my-image.png");
    
    0 讨论(0)
  • 2020-11-22 10:06

    Want to share my experience and help someone stuck on the downloads not working in Firefox and updated answer to 2014. The below snippet will work in both firefox and chrome and it will accept a filename:

      // Construct the <a> element
      var link = document.createElement("a");
      link.download = thefilename;
      // Construct the uri
      var uri = 'data:text/csv;charset=utf-8;base64,' + someb64data
      link.href = uri;
      document.body.appendChild(link);
      link.click();
      // Cleanup the DOM
      document.body.removeChild(link);
    
    0 讨论(0)
提交回复
热议问题