Using HTML5/Javascript to generate and save a file

2018-12-31 02:03发布

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 converting files to a easier to use format (probably JSON). Thing is, I already have the code to parse the file in Javascript, so I may as well use it as my exporter too! The problem is saving.

Now, I know that I can parse the file, send the result to the server, and have the browser request the file back from the server as a download. But in reality the server has nothing to do with this particular process, so why get it involved? I already have the contents of the desired file in memory. Is there any way that I could present the user with a download using pure javascript? (I doubt it, but might as well ask...)

And to be clear: I am not trying to access the filesystem without the users knowledge! The user will provide a file (probably via drag and drop), the script will transform the file in memory, and the user will be prompted to download the result. All of which should be "safe" activities as far as the browser is concerned.

[EDIT]: I didn't mention it upfront, so the posters who answered "Flash" are valid enough, but part of what I'm doing is an attempt to highlight what can be done with pure HTML5... so Flash is right out in my case. (Though it's a perfectly valid answer for anyone doing a "real" web app.) That being the case it looks like I'm out of luck unless I want to involve the server. Thanks anyway!

15条回答
看风景的人
2楼-- · 2018-12-31 02:35

You can use localStorage. This is the Html5 equivalent of cookies. It appears to work on Chrome and Firefox BUT on Firefox, I needed to upload it to a server. That is, testing directly on my home computer didn't work.

I'm working up HTML5 examples. Go to http://faculty.purchase.edu/jeanine.meyer/html5/html5explain.html and scroll to the maze one. The information to re-build the maze is stored using localStorage.

I came to this article looking for HTML5 JavaScript for loading and working with xml files. Is it the same as older html and JavaScript????

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 02:36
function download(content, filename, contentType)
{
    if(!contentType) contentType = 'application/octet-stream';
        var a = document.createElement('a');
        var blob = new Blob([content], {'type':contentType});
        a.href = window.URL.createObjectURL(blob);
        a.download = filename;
        a.click();
}
查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 02:37

This thread was invaluable to figure out how to generate a binary file and prompt to download the named file, all in client code without a server.

First step for me was generating the binary blob from data that I was saving. There's plenty of samples for doing this for a single binary type, in my case I have a binary format with multiple types which you can pass as an array to create the blob.

saveAnimation: function() {

    var device = this.Device;
    var maxRow = ChromaAnimation.getMaxRow(device);
    var maxColumn = ChromaAnimation.getMaxColumn(device);
    var frames = this.Frames;
    var frameCount = frames.length;

    var writeArrays = [];


    var writeArray = new Uint32Array(1);
    var version = 1;
    writeArray[0] = version;
    writeArrays.push(writeArray.buffer);
    //console.log('version:', version);


    var writeArray = new Uint8Array(1);
    var deviceType = this.DeviceType;
    writeArray[0] = deviceType;
    writeArrays.push(writeArray.buffer);
    //console.log('deviceType:', deviceType);


    var writeArray = new Uint8Array(1);
    writeArray[0] = device;
    writeArrays.push(writeArray.buffer);
    //console.log('device:', device);


    var writeArray = new Uint32Array(1);
    writeArray[0] = frameCount;
    writeArrays.push(writeArray.buffer);
    //console.log('frameCount:', frameCount);

    for (var index = 0; index < frameCount; ++index) {

      var frame = frames[index];

      var writeArray = new Float32Array(1);
      var duration = frame.Duration;
      if (duration < 0.033) {
        duration = 0.033;
      }
      writeArray[0] = duration;
      writeArrays.push(writeArray.buffer);

      //console.log('Frame', index, 'duration', duration);

      var writeArray = new Uint32Array(maxRow * maxColumn);
      for (var i = 0; i < maxRow; ++i) {
        for (var j = 0; j < maxColumn; ++j) {
          var color = frame.Colors[i][j];
          writeArray[i * maxColumn + j] = color;
        }
      }
      writeArrays.push(writeArray.buffer);
    }

    var blob = new Blob(writeArrays, {type: 'application/octet-stream'});

    return blob;
}

The next step is to get the browser to prompt the user to download this blob with a predefined name.

All I needed was a named link I added in the HTML5 that I could reuse to rename the initial filename. I kept it hidden since the link doesn't need display.

<a id="lnkDownload" style="display: none" download="client.chroma" href="" target="_blank"></a>

The last step is to prompt the user to download the file.

var data = animation.saveAnimation();
var uriContent = URL.createObjectURL(data);
var lnkDownload = document.getElementById('lnkDownload');
lnkDownload.download = 'theDefaultFileName.extension';
lnkDownload.href = uriContent;
lnkDownload.click();
查看更多
时光乱了年华
5楼-- · 2018-12-31 02:40

HTML5 defined a window.saveAs(blob, filename) method. It isn't supported by any browser right now. But there is a compatibility library called FileSaver.js that adds this function to most modern browsers (including Internet Explorer 10+). Internet Explorer 10 supports a navigator.msSaveBlob(blob, filename) method (MSDN), which is used in FileSaver.js for Internet Explorer support.

I wrote a blog posting with more details about this problem.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 02:40

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>

查看更多
何处买醉
7楼-- · 2018-12-31 02:40

Take a look at Doug Neiner's Downloadify which is a Flash based JavaScript interface to do this.

Downloadify is a tiny JavaScript + Flash library that enables the generation and saving of files on the fly, in the browser, without server interaction.

查看更多
登录 后发表回答