Using HTML5/JavaScript to generate and save a file

后端 未结 17 1720
有刺的猬
有刺的猬 2020-11-21 07:30

I\'ve been fiddling with WebGL lately, and have gotten a Collada reader working. Problem is it\'s pretty slow (Collada is a very verbose format), so I\'m going to start conv

相关标签:
17条回答
  • 2020-11-21 08:03

    You can generate a data URI. However, there are browser-specific limitations.

    0 讨论(0)
  • 2020-11-21 08:05

    I found two simple approaches that work for me. First, using an already clicked a element and injecting the download data. And second, generating an a element with the download data, executing a.click() and removing it again. But the second approach works only if invoked by a user click action as well. (Some) Browser block click() from other contexts like on loading or triggered after a timeout (setTimeout).

    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="UTF-8">
        <script type="text/javascript">
          function linkDownload(a, filename, content) {
            contentType =  'data:application/octet-stream,';
            uriContent = contentType + encodeURIComponent(content);
            a.setAttribute('href', uriContent);
            a.setAttribute('download', filename);
          }
          function download(filename, content) {
            var a = document.createElement('a');
            linkDownload(a, filename, content);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          }
        </script>
       </head>
      <body>
        <a href="#" onclick="linkDownload(this, 'test.txt', 'Hello World!');">download</a>
        <button onclick="download('test.txt', 'Hello World!');">download</button>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-11-21 08:07

    Saving large files

    Long data URIs can give performance problems in browsers. Another option to save client-side generated files, is to put their contents in a Blob (or File) object and create a download link using URL.createObjectURL(blob). This returns an URL that can be used to retrieve the contents of the blob. The blob is stored inside the browser until either URL.revokeObjectURL() is called on the URL or the document that created it is closed. Most web browsers have support for object URLs, Opera Mini is the only one that does not support them.

    Forcing a download

    If the data is text or an image, the browser can open the file, instead of saving it to disk. To cause the file to be downloaded upon clicking the link, you can use the the download attribute. However, not all web browsers have support for the download attribute. Another option is to use application/octet-stream as the file's mime-type, but this causes the file to be presented as a binary blob which is especially user-unfriendly if you don't or can't specify a filename. See also 'Force to open "Save As..." popup open at text link click for pdf in HTML'.

    Specifying a filename

    If the blob is created with the File constructor, you can also set a filename, but only a few web browsers (including Chrome & Firefox) have support for the File constructor. The filename can also be specified as the argument to the download attribute, but this is subject to a ton of security considerations. Internet Explorer 10 and 11 provides its own method, msSaveBlob, to specify a filename.

    Example code

    var file;
    var data = [];
    data.push("This is a test\n");
    data.push("Of creating a file\n");
    data.push("In a browser\n");
    var properties = {type: 'text/plain'}; // Specify the file's mime-type.
    try {
      // Specify the filename using the File constructor, but ...
      file = new File(data, "file.txt", properties);
    } catch (e) {
      // ... fall back to the Blob constructor if that isn't supported.
      file = new Blob(data, properties);
    }
    var url = URL.createObjectURL(file);
    document.getElementById('link').href = url;
    <a id="link" target="_blank" download="file.txt">Download</a>

    0 讨论(0)
  • 2020-11-21 08:07

    Here is a link to the data URI method Mathew suggested, it worked on safari, but not well because I couldn't set the filetype, it gets saved as "unknown" and then i have to go there again later and change it in order to view the file...

    http://www.nihilogic.dk/labs/canvas2image/

    0 讨论(0)
  • 2020-11-21 08:09

    Here is a tutorial to export files as ZIP:

    Before getting started, there is a library to save files, the name of library is fileSaver.js, You can find this library here. Let's get started, Now, include the required libraries:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js"  type="text/javascript"></script>
    <script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>
    

    Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.

    <script type="text/javascript">
        var zip = new JSZip();
        zip.file("Hello.txt", "Hello World\n");
        zip.generateAsync({type:"blob"})
        .then(function(content) {
            // see FileSaver.js
            saveAs(content, "file.zip");
        });
    </script>
    

    This will download a file called file.zip. You can read more here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library

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