HTML5 File API Downloading File from Server and Saving It in Sandbox

HTML5 File API downloading file from server and saving it in sandbox

I'm going to show you how to download files with the XMLHttpRequest Level 2 and save them with the FileSystem API or with the FileSaver interface.

##Downloading Files##

To download a file you will use the XMLHttpRequest Level 2 (aka XHR2), which supports cross-origin requests, uploading progress events, and uploading/downloading of binary data. In the post "New Tricks in XMLHttpRequest2" there's plenty of examples of use of XHR2.

To download a file as a blob all you have do to is specify the responseType to "blob". You can also use the types "text", "arraybuffer" or "document". The function below downloads the file in the url and sends it to the success callback:

function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}
};
xhr.send(null);
}

The success callback will receive as argument an instance of Blob that can be later modified and saved and/or uploaded to a server.

##Saving Files with the FileSystem API##

As the Can i use... site points out there aren't many browsers with support to the FileSystem API. For Firefox there's an explanation for the lack of support. So, you will have to use Chrome to do this.

First you will have to request a storage space, it can be either temporary or persistent. You will probably want to have a persistent storage, in this case you will have request a quota of storage space upfront (some facts):

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.storageInfo = window.storageInfo || window.webkitStorageInfo;

// Request access to the file system
var fileSystem = null // DOMFileSystem instance
, fsType = PERSISTENT // PERSISTENT vs. TEMPORARY storage
, fsSize = 10 * 1024 * 1024 // size (bytes) of needed space
;

window.storageInfo.requestQuota(fsType, fsSize, function(gb) {
window.requestFileSystem(fsType, gb, function(fs) {
fileSystem = fs;
}, errorHandler);
}, errorHandler);

Now that you have access to the file system you can save and read files from it. The function below can save a blob in the specified path into the file system:

function saveFile(data, path) {
if (!fileSystem) return;

fileSystem.root.getFile(path, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.write(data);
}, errorHandler);
}, errorHandler);
}

And to read a file by its path:

function readFile(path, success) {
fileSystem.root.getFile(path, {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();

reader.onloadend = function(e) {
if (success) success(this.result);
};

reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}

In addition to the readAsText method, according to the FileReader API you can call readAsArrayBuffer and readAsDataURL.

##Using the FileSaver##

The post "Saving Generated Files on Client-Side" explains very well the use of this API. Some browsers may need the FileSaver.js in order to have the saveAs interface.

If you use it together with the downloadFile function, you could have something like this:

downloadFile('image.png', function(blob) {
saveAs(blob, "image.png");
});

Of course it would make more sense if the user could visualize the image, manipulate it and then save it in his drive.

###Error Handler###

Just to fulfill the example:

function errorHandler(e) {
var msg = '';

switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};

console.log('Error: ' + msg);
}

##Useful links##

  • Saving Generated Files on the Client-Side
  • Exploring the FileSystem APIs
  • New Tricks in XMLHttpRequest2
  • Reading Files in JavaScript Using the File APIs

File API, programaticly download file from server and store it in sandboxed file system

You want XMLHttpRequest(), which despite its name, can handle downloading all types of data including binary. If you set the responseType to "arraybuffer", you can convert that to a blob and save it to the file system pretty easily.

HTML5Rocks has a great tutorial that should cover everything you need:
New Tricks in XMLHttpRequest

(I know this question is a bit old, but I was just searching for how to do the same thing and it was the first result that popped up, so I thought I'd share)

HTML5 FS API: Let the user create files outside of the sandbox?

How about an "a" element with a download attribute, and using FileEntry.toURL() to populate the href target?

Best practice to load video from filesystem API

You're asking about persistent, client-side storage of video, specifically using the Directories and System API, sometimes called "File System API." I believe this is currently only supported on Chrome 28 and Opera 16 or higher – i.e., slightly less than 1 in 3 web users right now.

Per the API spec, the users will be prompted to allow the quota for the on-client storage allotment because you're requesting persistent, not transient, storage. While the persistent client storage may be handy, it's not entirely transparent to the user.

As for determining if the Chrome or Opera user has the video stored locally, simply calling getFile() file will do it; if the file doesn't exist, it simply throws an error that you can then handle to go ahead and pull down the video. That's the standard / best practice way of determining if a file has been stored locally.

PS: Yes, I see that Blackberry mobile supports the API, too. I just don't know if either of the remaining Blackberry users will have the device storage quota available for video :-)

Using HTML5/JavaScript to generate and save a file

OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:

1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).

2) Build the data URI:

uriContent = "data:application/octet-stream," + encodeURIComponent(content);

There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.

3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:

newWindow = window.open(uriContent, 'neuesDokument');

That's it.

How to send a single file from one client browser to another without saving it on server (node.js) using html5 and File API

Websockets are the only way I can imagine doing this, and you'd still need a server-side proxy.

See: Do websockets allow for p2p (browser to browser) communication?



Related Topics



Leave a reply



Submit