7

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

2
  • 2
    Can you explain what you mean by "file object"? Commented Jul 8, 2016 at 9:38
  • That I get after uploading from form.. The file object Commented Jul 8, 2016 at 9:43

2 Answers 2

9

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);
Sign up to request clarification or add additional context in comments.

1 Comment

var file from bfmags answer is File object
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.