简体   繁体   中英

Convert url to file object with 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


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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM