Convert an url to blob url object

This piece of code could be used to convert a URL to blob URL and get file in blob 
    var xhr = new XMLHttpRequest;
    xhr.responseType = 'blob';
    xhr.onload = function () {
        var recoveredBlob = xhr.response;
        var blobUrl = URL.createObjectURL(recoveredBlob);
    };
    xhr.open('GET''https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvqNf3kxEV4wZGwGscm3r82l87kFfVBFeWuhCfrAnQbDtnE4kZUgxhxbqLXHWMXT83uKM98w77D8izfL6U4Y2RKtZKMkRNfc2pKHMaRJ7U07rEn1WOeH-WJOXcSSSvXxRj2e6Vw9yeVsM/s1600/1595756336067022-0.png');
    xhr.send();


This is a simple example but very useful when we need a file with blob type. In this example we just converting and url to blob url. This is useful to get shorted and secure link and can be used in html anchor tag.

Approach

1. Get xmlHttpRequest object and story to xhr. This is http client object used to send http request 
2. Set blob type in xhr.responseType this will make the to be returned in blob
3. Pass a function to xhr.onload method this function is called when request is send and have a response.
4. Pass url with get type in xhr.open method and then send the request xhr.send
5. As response from server onload method will be called and in this function use xhr.response property to take the server response in Blob type.
6. Now convert this response into blob url using Url.createObjectUrl method.

Comments

Post a Comment