Convert url to file object with JavaScript - javascript

I have converted an image into dataurl using FileReader and it gives me output like:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlā€¦Vp1m8u4+SV/s0TpD8+91R/3Xlf8sXZv9Y9OGLk5eyVnCNu19Ntdu2jYOnaHtG7ffb7t/uP/9k=
Which is a very long string..
Now I again want to convert it to file object so that I can post this image.
How can I again convert this image into file object

Converting dataurl to File Object
https://jsfiddle.net/fn2aonwy/
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ia], { type: 'image/jpeg' });
var file = new File([blob], "image.jpg");
based on #William-t answer / more discussion on stackoverflow.com/questions/4998908/
MDN blob file
A Blob object represents a file-like object of immutable, raw data.
Blobs represent data that isn't necessarily in a JavaScript-native
format. The File interface is based on Blob, inheriting blob
functionality and expanding it to support files on the user's system.
MDN FormData
var form = new FormData(),
request = new XMLHttpRequest();
form.append("image", blob, "myimage.jpg");
request.open("POST", "/upload", true);
request.send(form);

You can use fetch to convert an url to a File object.
//load src and convert to a File instance object
//work for any type of src, not only image src.
//return a promise that resolves with a File instance
function srcToFile(src, fileName, mimeType){
return (fetch(src)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], fileName, {type:mimeType});})
);
}
//usage example: (works in Chrome and Firefox)
srcToFile(
'data:image/gif;base64,R0lGODlhDgANAKIAAAAAAP///9HV2U5RU////wAAAAAAAA'
+ 'AAACH5BAEAAAQALAAAAAAOAA0AAAMXSLrc/hCO0Wa1atJLtdTbF0ZjZJ5oyiQAOw==',
'arrow.gif',
'image/gif'
)
.then(function(file){
console.log(file);
})

Related

Converting from blob to pdf

I'am able to convert my pdf files into blob. But what i want to do is the opposite by converting it from blob to pdf.
Here is my code converting it from pdf to blob. I just need some advice where i can return from blob to pdf.
var xhr=new XMLHttpRequest();
xhr.open("GET","./template.pdf");
xhr.responseType="arraybuffer";
xhr.onload = function (e){
var blob = new Blob([xhr.response]);
var url = URL.createObjectURL(blob)
console.log(url);
var embed=document.getElementById("template");
embed.src = url;
}
xhr.send();
The result will return a blob from console=> blob:http://localhost:8081/d42939da-e318-4d88-b46f-8240efaa7b1c and once i paste this on the url, it will show me a huge blob text
You can set the content type when creating the blob to tell it is a pdf.
var blob = new Blob([xhr.response], { type: 'application/pdf' });

create and automatically force download file using js

I have used HTML file reader API to read the file,
and i got the below result
data:application/pdf;base64,JVBERi0xLjYNJeLjz9MNCjE2OSAwIG9iaiA8PC9MaW5lYXJpemVkIDEvTCAyMDgwNTMxL08gMTczL0UgMjg1ODM3L04gMjQvVCAyMDc3MDkyL0ggWyAxMTM2IDc1OV0+Pg1lbmRvYmoNICAgICAgICAgIA14cmVmDTE2OSA0Mg0wMDAwMDAwMDE2IDAwMDAwIG4NCjAwMDAwMDE4OTUgMDAwMDAgbg0KMDAwMDAwMjAzMSAwMDAwMCBuDQowMDAwMDAyMTY0IDAwMDAwIG4NCjAwMDAwMDIzMTkgMDAwMDAgbg0KMDAwMDAwMjgzOCAwMDAwMCBuDQowMDAwMDAyODY0IDAwMDAwIG4NCjAwMDAwMDM3OTAgMDAwMDAgbg0KMDAwMDAwNDMyNCAwMDAwMCBuDQowMDAwMDA0NDE1IDAwMDAwIG4NCjAwMDAwMDU2MDcgMDAwMDAgbg0KMDAwMDAwNTY1MiAwMDAwMCBuDQowMDAwMDA1Njc3IDAwMDAwIG4NCjAwMDAwMDU3OTUgMDAwMDAgbg0KMDAwMDAwNTg0NSAwMDAwMCBuDQowMDAwMDA1ODcwIDAwMDAwIG4NCjAwMDAwMDU5ODYgMDAwMDAgbg0KMDAwMDAwNzQxOSAwMDAwMCBuDQowMDAwMDA3Nzk4IDAwMDAwIG4NCjAwMDAwMDgxMDQgMDAwMDAgbg0KMDAwMDAwODQxMyAwMDAwMCBuDQowMDAwMDA4OTQ0IDAwMDA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1MzEgMDAwMDAgbg0KMDAwMjA3MDU1MiAwMDAwMCBuDQowMDAyMDcwNTc4IDAwMDAwIG4NCjAwMDIwNzY4NDMgMDAwMDAgbg0KdHJhaWxlcg08PC9TaXplIDE2OS9FbmNyeXB0IDE3MCAwIFI+Pg1zdGFydHhyZWYNMTE2DSUlRU9GDQ==
How to write a file and force download the same file using the above string?
Warning: I don't have IE available to test with, but this was based off code that DOES work under IE.
My DataURL is an image so I had to change out the header. You might not have to with your header -- but I left the code in place so you could see how it was done.
Thanks to IE, you need two different processes.
On IE, you convert your DataURI to a blob then download the blob.
On everything else, you would just download the URI itself.
document.getElementById("d_button").addEventListener("click", download);
var filename="testfile";
// FROM http://stackoverflow.com/questions/12168909/blob-from-dataurl
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {
type: mimeString
});
return blob;
// Old code
// var bb = new BlobBuilder();
// bb.append(ab);
// return bb.getBlob(mimeString);
}
const dataURI = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
function download() {
if (window.navigator.msSaveBlob) { // for IE
const blob = dataURItoBlob(dataURI);
window.navigator.msSaveBlob(blob, `${filename}.png`);
return;
}
let dt = dataURI;
/* Change MIME type to trick the browser to downlaod the file instead of displaying it */
dt = dt.replace(/^data:image\/[^;]*/, "data:application/octet-stream");
/* In addition to <a>'s "download" attribute, you can define HTTP-style headers */
dt = dt.replace(/^data:application\/octet-stream/, `data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=${filename}.png`);
this.href = dt;
}
Download this
I got answer using <a> tag force the download the file.
var element = document.createElement('a');
element.setAttribute('href',text );
element.setAttribute('download', filename);
element.setAttribute('target', '_blank');
element.style.display = 'none';
document.body.appendChild(element);
$("#page_header").removeClass('loader');
element.click();
I got another answer using force the download the file.
using this link install file saver (https://www.npmjs.com/package/file-saver)
result : 'data:application/pdf;base64,JVBERi0xLjYNJeLjz9MNCjE2OSAwIG9iaiA8PC9MaW5lYXJpemVkIDEvTCAyMDgwNTMxL08gMTczL0UgMjg1ODM3L04gMjQvVCAyMDc3MDkyL0ggWyAxMTM2IDc1OV0+Pg1lbmRvYmoNICAgICAgICAgIA14cmVmDTE2OSA0Mg0wMDAwMDAwMDE2IDAwMDAwIG4NCjAwMDAwMDE4OTUgMDAwMDAgbg0KMDAwMDAwMjAzMSAwMDAwMCBuDQowMDAwMDAyMTY0IDAwMDAwIG4NCjAwMDAwMDIzMTkgMDAwMDAgbg0KMDAwMDAwMjgzOCAwMDAwMCBuDQowMDAwMDAyODY0IDAwMDAwIG4NCjAwMDAwMDM3OTAgMDAwMDAgbg0KMDAwMDAwNDMyNCAwMDAwMCBuDQowMDAwMDA0NDE1IDAwMDAwIG4NCjAwMDAwMDU2MDcgMDAwMDAgbg0KMDAwMDAwNTY1MiAwMDAwMCBuDQowMDAwMDA1Njc3IDAwMDAwIG4NCjAwMDAwMDU3OTUgMDAwMDAgbg0KMDAwMDAwNTg0NSAwMDAwMCBuDQowMDAwMDA1ODcwIDAwMDAwIG4NCjAwMDAwMDU5ODYgMDAwMDAgbg0KMDAwMDAwNzQxOSAwMDAwMCBuDQowMDAwMDA3Nzk4IDAwMDAwIG4NCjAwMDAwMDgxMDQgMDAwMDAgbg0KMDAwMDAwODQxMyAwMDAwMCBuDQowMDAwMDA4OTQ0IDAwMDAwIG4NCjAwMDAwMDk2NTAgMDAwMDAgbg0KMDAwMDAxMDA1NiAwMDAwMCBuDQowMDAwMDEwMjIxIDAwMDAwIG4NCjAwMDAwMT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0KdHJhaWxlcg08PC9TaXplIDE2OS9FbmNyeXB0IDE3MCAwIFI+Pg1zdGFydHhyZWYNMTE2DSUlRU9GDQ=='
file_name : 'sample.jpg'
fileType : 'image/jpeg'
**Function Call**
this.urltoFile(result, file_name, fileType)
.then(function(file){
var blob = new Blob ([file], {type: fileType});
FileSaver.saveAs(blob, file_name);
this.loading = false;
});
**function definition**
urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
)},

How to create File object from Blob?

DataTransferItemList.add allows you to override copy operation in javascript. It, however, only accepts File object.
Copy event
The code in my copy event:
var items = (event.clipboardData || event.originalEvent.clipboardData);
var files = items.items || items.files;
if(files) {
var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));
files.add(blob);
}
The error in chrome:
Uncaught TypeError: Failed to execute add on DataTransferItemList: parameter 1 is not of type File.
Trying the new File(Blob blob, DOMString name)
In Google Chrome I tried this, according to the current specification:
var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));
var file = new File(blob, "image.png");
Problem here is, that Google Chrome doesn't stick to specifications very much.
Uncaught TypeError: Failed to construct File: Illegal constructor
Neither does Firefox in this case:
The method parameter is missing or invalid.
Trying the new File([Mixed blobParts], DOMString name, BlobPropertyBag options)
Solution suggested by #apsillers doesn't work too. This is non stadard method used (but useless) in both Firefox and Chrome.
Binary data
I tried to avoid blob, but the file constructor failed anyway:
//Canvas to binary
var data = atob( //atob (array to binary) converts base64 string to binary string
_this.editor.selection.getSelectedImage() //Canvas
.toDataURL("image/png") //Base64 URI
.split(',')[1] //Base64 code
);
var file = new File([data], "image.png", {type:"image/png"}); //ERROR
You can try that in console:
Chrome <38:
Chrome >=38:
Firefox:
Blob
Passing Blob is probably correct and works in Firefox:
var file = new File([new Blob()], "image.png", {type:"image/png"});
Firefox:
Chrome <38:
Chrome >=38:
Q: So how can I make File from Blob?
Note: I added more screenshots after #apsillers reminded me to update Google Chrome.
The File constructor (as well as the Blob constructor) takes an array of parts. A part doesn't have to be a DOMString. It can also be a Blob, File, or a typed array. You can easily build a File out of a Blob like this:
new File([blob], "filename")
This was the complete syntax which I had to use to convert a blob into a file, which I later had to save to a folder using my server.
var file = new File([blob], "my_image.png",{type:"image/png", lastModified:new Date().getTime()})
this works with me, from canvas to File [or Blob], with filename!
var dataUrl = canvas.toDataURL('image/jpeg');
var bytes = dataUrl.split(',')[0].indexOf('base64') >= 0 ?
atob(dataUrl.split(',')[1]) :
(<any>window).unescape(dataUrl.split(',')[1]);
var mime = dataUrl.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++) {
ia[i] = bytes.charCodeAt(i);
}
var newImageFileFromCanvas = new File([ia], 'fileName.jpg', { type: mime });
Or if you want a blob
var blob = new Blob([ia], { type: mime });

Chrome Extension Blob data issue

I am trying to create a blob from a canvas image from within a Chrome extension, however I am getting an error "Uncaught TypeError: object is not a function" when trying to create a Blob using any method!
var blob = new Blob();
var blob = new Blob(['body { color: red; }'], {type: 'text/css'});
are two examples that fail with the above error. I am actually trying to convert a DataURL to a blob so the code I am using (which also fails) is...
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
I am assuming that Chrome will not support new blobs??
The issue was that the call to create a Blob was being done from a JS file, the correct place was the background JavaScript file. By moving the method to create the blob into the background file I as able to use it.

Blob from DataURL?

Using FileReader's readAsDataURL() I can transform arbitrary data into a Data URL. Is there way to convert a Data URL back into a Blob instance using builtin browser apis?
User Matt has proposed the following code a year ago ( How to convert dataURL to file object in javascript? ) which might help you
EDIT: As some commenters reported, BlobBuilder has been deprecated some time ago. This is the updated code:
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
// create a view into the buffer
var ia = new Uint8Array(ab);
// set the bytes of the buffer to the correct values
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {type: mimeString});
return blob;
}
Like #Adria method but with Fetch api and just smaller [caniuse?]
Don't have to think about mimetype since blob response type just works out of the box
Warning: Can violate the Content Security Policy (CSP)
...if you use that stuff
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
fetch(url)
.then(res => res.blob())
.then(blob => console.log(blob))
Don't think you could do it any smaller then this without using lib's
In modern browsers one can use the one liner suggested by Christian d'Heureuse in a comment:
const blob = await (await fetch(dataURI)).blob();
dataURItoBlob : function(dataURI, dataTYPE) {
var binary = atob(dataURI.split(',')[1]), array = [];
for(var i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
return new Blob([new Uint8Array(array)], {type: dataTYPE});
}
input dataURI is Data URL and dataTYPE is the file type and then output blob object
XHR based method.
function dataURLtoBlob( dataUrl, callback )
{
var req = new XMLHttpRequest;
req.open( 'GET', dataUrl );
req.responseType = 'arraybuffer'; // Can't use blob directly because of https://crbug.com/412752
req.onload = function fileLoaded(e)
{
// If you require the blob to have correct mime type
var mime = this.getResponseHeader('content-type');
callback( new Blob([this.response], {type:mime}) );
};
req.send();
}
dataURLtoBlob( 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', function( blob )
{
console.log( blob );
});
try:
function dataURItoBlob(dataURI) {
if(typeof dataURI !== 'string'){
throw new Error('Invalid argument: dataURI must be a string');
}
dataURI = dataURI.split(',');
var type = dataURI[0].split(':')[1].split(';')[0],
byteString = atob(dataURI[1]),
byteStringLength = byteString.length,
arrayBuffer = new ArrayBuffer(byteStringLength),
intArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteStringLength; i++) {
intArray[i] = byteString.charCodeAt(i);
}
return new Blob([intArray], {
type: type
});
}
Since none of these answers support base64 and non-base64 dataURLs, here's one that does based on vuamitom's deleted answer:
// from https://stackoverflow.com/questions/37135417/download-canvas-as-png-in-fabric-js-giving-network-error/
var dataURLtoBlob = exports.dataURLtoBlob = function(dataurl) {
var parts = dataurl.split(','), mime = parts[0].match(/:(.*?);/)[1]
if(parts[0].indexOf('base64') !== -1) {
var bstr = atob(parts[1]), n = bstr.length, u8arr = new Uint8Array(n)
while(n--){
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {type:mime})
} else {
var raw = decodeURIComponent(parts[1])
return new Blob([raw], {type: mime})
}
}
Note: I'm not sure if there are other dataURL mime types that might have to be handled differently. But please let me know if you find out! Its possible that dataURLs can simply have any format they want, and in that case it'd be up to you to find the right code for your particular use case.
Create a blob using XHR API:
function dataURLtoBlob( dataUrl, callback )
{
var req = new XMLHttpRequest;
req.open( 'GET', dataUrl );
req.responseType = 'blob';
req.onload = function fileLoaded(e)
{
callback(this.response);
};
req.send();
}
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
dataURLtoBlob(dataURI , function( blob )
{
console.log( blob );
});
If you need something that works server-side on Google Apps Script, try:
function dataURItoBlob(dataURI) {
// convert base64 to Byte[]
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var data = Utilities.base64Decode(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var blob = Utilities.newBlob(data);
blob.setContentType(mimeString);
return blob;
}
use
FileReader.readAsArrayBuffer(Blob|File)
rather than
FileReader.readAsDataURL(Blob|File)

Categories

Resources