Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm going to show you how to download files with the <a href="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html">XMLHttpRequest Level 2</a> and save them with the <a href="http://dev.w3.org/2009/dap/file-system/pub/FileSystem/">FileSystem API</a> or with the <a href="https://github.com/eligrey/FileSaver.js">FileSaver interface</a>.</p> <h2>Downloading Files</h2> <p>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 "<a href="http://www.html5rocks.com/en/tutorials/file/xhr2/">New Tricks in XMLHttpRequest2</a>" there's plenty of examples of use of XHR2.</p> <p>To download a file as a blob all you have do to is specify the <code>responseType</code> to "blob". You can also use the types "text", "arraybuffer" or "document". The function below downloads the file in the <code>url</code> and sends it to the <code>success</code> callback:</p> <pre><code>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); } </code></pre> <p>The <code>success</code> callback will receive as argument an instance of Blob that can be later modified and saved and/or uploaded to a server.</p> <h2>Saving Files with the FileSystem API</h2> <p>As the <em>Can i use...</em> site <a href="http://caniuse.com/filesystem">points out</a> there aren't many browsers with support to the FileSystem API. For Firefox <a href="https://hacks.mozilla.org/2012/07/why-no-filesystem-api-in-firefox/">there's an explanation</a> for the lack of support. So, you will have to use Chrome to do this.</p> <p>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 (<a href="http://updates.html5rocks.com/2011/11/Quota-Management-API-Fast-Facts">some facts</a>):</p> <pre><code>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); </code></pre> <p>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:</p> <pre><code>function saveFile(data, path) { if (!fileSystem) return; fileSystem.root.getFile(path, {create: true}, function(fileEntry) { fileEntry.createWriter(function(writer) { writer.write(data); }, errorHandler); }, errorHandler); } </code></pre> <p>An to read a file by it's path:</p> <pre><code>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); } </code></pre> <p>In addition to the <code>readAsText</code> method, according to the <a href="http://dev.w3.org/2006/webapi/FileAPI/#dfn-filereader">FileReader API</a> you can call <code>readAsArrayBuffer</code> and <code>readAsDataURL</code>.</p> <h2>Using the FileSaver</h2> <p>The post "<a href="http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side">Saving Generated Files on Client-Side</a>" explains very well the use of this API. Some browsers may need the <a href="https://github.com/eligrey/FileSaver.js">FileSaver.js</a> in order to have the <code>saveAs</code> interface.</p> <p>If you use it together with the <code>downloadFile</code> function, you could have something like this:</p> <pre><code>downloadFile('image.png', function(blob) { saveAs(blob, "image.png"); }); </code></pre> <p>Of course it would make more sense if the user could visualize the image, manipulate it and then save it in his drive.</p> <h3>Error Handler</h3> <p>Just to fulfill the example:</p> <pre><code>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); } </code></pre> <h2>Useful links</h2> <ul> <li><a href="http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side">Saving Generated Files on the Client-Side</a></li> <li><a href="http://www.html5rocks.com/en/tutorials/file/filesystem/">Exploring the FileSystem APIs</a></li> <li><a href="http://www.html5rocks.com/en/tutorials/file/xhr2/">New Tricks in XMLHttpRequest2</a></li> <li><a href="http://www.html5rocks.com/en/tutorials/file/dndfiles/">Reading Files in JavaScript Using the File APIs</a></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload