QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Javascript Create File Object From URL

Javascript Create File Object From URL

In this tutorial I will show you how to retrieve a remote file and then create a blob(similar to file object).

This can be useful if you want to analyze a text/binary remote file on frontend using JavaScript.

This simple code converts a remote file to a blob object.

var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "/favicon.png");
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function()
{
    blob = xhr.response;//xhr.response is now a blob object
}
xhr.send();

If the blob is representing a binary file then you need to copy the content of the blob into a ArrayBuffer and then analyze it.

var myReader = new FileReader();
myReader.readAsArrayBuffer(blob)
myReader.addEventListener("loadend", function(e)
{
        var buffer = e.srcElement.result;//arraybuffer object
});

If the blob is representing a text file then you can retrieve its content as a string and analyze it.

var myReader = new FileReader();
myReader.addEventListener("loadend", function(e){
    var str = e.srcElement.result;
});
myReader.readAsText(blob);
Oct 20, 2014Narayan Prusty
requestAnimationFrame DelayCreating a One Page WordPress Theme
Comments: 1
  1. Ron
    5 years ago

    I don’t get it.. How can you download the /favicon.png? Let say I have a url blabla.com/blabla.jpg and I want it to convert into Blob and download the image.. Is it even possible?

    ReplyCancel

Leave a Reply to Ron Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

8 years ago 1 Comment Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
Related Articles
  • Passphrase Based Encryption using Web Cryptography API
  • Symmetric Encryption using Web Cryptography API
  • Remove HTML Tags from String using PHP
  • Adding Custom Content to Printed Web Pages
  • Asymmetric Encryption using Web Cryptography API
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license