Meta

Displaying XHR Downloaded Images Using the File API

Last time, we proposed adding progress events on the image element to avoid the complexity of using XHR to monitor image download progress. In order to display the image in the XHR approach, we used base 64 encoding to convert the binary image data into a data URI. Then, we passed the data URI to the image element’s src attribute.

Another XHR-based approach uses the new File API to simplify displaying the image. It displays the image like this:

Create an object URL for the binary image data (blob) from the XHR response.

Set the src attribute of the image tag to the new object URL.

Clean up the blob after the image loads it.

This approach looks like this:

imgElement.src = window.URL.createObjectURL(request.response);

For createObjectURL() to function, you also need to set the XHR’s responseType to “blob” before you send the request, which looks like:

request.responseType = "blob";

Once the image is done loading the blob from its object URL, we need to clean up the blob, which looks like:

You can view a full sample and its source here. The sample monitors an image’s download progress using XHR and displays the image using the File API approach. Note that this sample relies on the current drafts of the File API and XHR2 specs, and will not work in most current browsers because not all of their features that have been released yet. For Chrome/Safari/WebKit users, note that window.URL is currently window.webkitURL.

Although this approach is already much better than base 64 encoding, it still lacks the ease-of-use of the image progress events proposal that we discussed in the previous post. To recap, the proposal defines progress events such as onloadstart, progress, and onloadend directly on the image element. Its specific advantage over the XHR + File API approach is:

No need to create a blob and clean it up right after the image element loads it.

As before, the proposal’s advantages over any XHR approach like this one include: