In this blog, I have explained How to Use BlobURl to preview file or download file.
In the browser, on web page, when we need to preview or download file then, we deal with file as dataURl which consist the content-type followed by Base64 string as file content. But, Data URL that contains base64 string, can be very large and handling it (like sending one page to another in URL) can be time consuming. Additionally, we cannot have large string in URL.
Instead of large size Base64 string to preview or download the file we can use BlobURL. Blob object contains the file content and we can use it as URL which is a BlobURL to upload/download data and also, we can used as ‘src’ to <img> tag to show image file.
Blob object syntax :
Let blob = new Blob(blobParts, options);
We meet binary data mostly while dealing with files. We can convert binary data to Blob as below:
Let’s assume variable “binary” is binary data of a pdf file.
const byteArrays = [];
for (let offset = 0; offset < binary.length; offset += 1024) {
const slice = binary.slice(offset, offset + 1024);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const contentType = ‘application/pdf’;
const blob = new Blob(byteArrays, { type: contentType });
We also can convert a DataURI or base64 string to blob object.
Assume, dataURI = “data:image/jpeg;base64,TWFuIGlzIGRpc3Rpbmd1aXNoZWQsI…..”
var byteString = atob(dataURI.split(‘,’)[1]);
var ArrayBuffer = new ArrayBuffer(byteString.length);
var bytes = new Uint8Array(ArrayBuffer);
for (var i = 0; i < byteString.length; i++) {
bytes[i] = byteString.charCodeAt(i);
}
const blob = Blob([ab], { type: ‘image/jpeg’ });
Now, we can easily convert blob object to BlobURL. We can do that using URL.createObjectURL(). We need to pass blob object to this method. It will return BlobURL.
const BlobURL = URL.createObjectURL(blob);
it will creates a unique URL for it, in the form blob:<origin>/<uuid>. It will looks like as follows:
“blob:https://javascript.info/1e67e00e-860d-40a5-89ae-6ab0cbee6273”