Using HTML5/JavaScript to generate and save a file

后端 未结 17 1749
有刺的猬
有刺的猬 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: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;
    Download

提交回复
热议问题