11

In a Google chrome extension I am working on, a file is downloaded from a server with an XMLHttpRequest. This file contains some binary data which are stored in an ArrayBuffer object. In order to provide the possibility to download this file I am using the createObjectURL API.

function publish(data) {
  if (!window.BlobBuilder && window.WebKitBlobBuilder) {
    window.BlobBuilder = window.WebKitBlobBuilder;
  }
  var builder = new BlobBuilder();
  builder.append(data);
  var blob = builder.getBlob();
  var url = window.webkitURL.createObjectURL(blob);
  $("#output").append($("<a/>").attr({href: url}).append("Download"));

}

It is working fine; except that the filename is an opaque UUID like 9a8f6a0f-dd0c-4715-85dc-7379db9ce142. Is there any way to force this filename to something more user-friendly?

1
  • 3
    BlobBuilder is outdated. Use the Blob constructor. Commented Mar 7, 2013 at 4:37

2 Answers 2

12

you can force an arbitrary filename by setting the "download" attribute of your anchor

see: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

Sign up to request clarification or add additional context in comments.

Comments

7

I have never tried it before, but it should be possible to create a new File object (which allows you to specify a file name) and write your blob to it. Something along the lines of:

function publish(data, filename) {

    if (!window.BlobBuilder && window.WebKitBlobBuilder) {
        window.BlobBuilder = window.WebKitBlobBuilder;
    }

    fs.root.getFile(filename, {
        create: true
    }, function (fileEntry) {

        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function (fileWriter) {

            fileWriter.onwriteend = function (e) {
                console.log('Write completed.');
            };

            fileWriter.onerror = function (e) {
                console.log('Write failed: ' + e.toString());
            };

            var builder = new BlobBuilder();
            builder.append(data);
            var blob = builder.getBlob();
            fileWriter.write(blob);

        }, errorHandler);

    }, errorHandler);
}

I think this could work for you.

1 Comment

Thank you, our solution works. Actually I already looked at this API but the toURL() method of the FileEntry interface didn't seem to work. After some googleing I figured out that this method has been renamed toURI() on Chrome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.