How to convert dataURL to file object in javascript?

Asked
Active3 hr before
Viewed126 times

8 Answers

convertobjectjavascript
90%

use dataURLtoBlob() function to convert dataURL to blob and send ajax to server.,File object is inherit from Blob object. You can use both of them with FormData object.,Then just append the blob to a new FormData object and post it to your server using ajax:,If you need to send it over ajax, then there's no need to use a File object, only Blob and FormData objects are needed.

As I sidenote, why don't you just send the base64 string to the server over ajax and convert it to binary server-side, using PHP's base64_decode for example? Anyway, the standard-compliant code from this answer works in Chrome 13 and WebKit nightlies:

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

   //Old Code
   //write the ArrayBuffer to a blob, and you're done
   //var bb = new BlobBuilder();
   //bb.append(ab);
   //return bb.getBlob(mimeString);

   //New Code
   return new Blob([ab], {
      type: mimeString
   });

}

Then just append the blob to a new FormData object and post it to your server using ajax:

var blob = dataURItoBlob(someDataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();

fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);
load more v
88%

I need to convert a dataURL to a File object in Javascript in order to send it over using AJAX. Is it possible? If yes, please tell me how.,use dataURLtoBlob() function to convert dataURL to blob and send ajax to server.,If you really want to convert the dataURL into File object.,Usage example 2: Convert to file object and upload to server

As I sidenote, why don't you just send the base64 string to the server over ajax and convert it to binary server-side, using PHP's base64_decode for example? Anyway, the standard-compliant code from this answer works in Chrome 13 and WebKit nightlies:

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

   //Old Code
   //write the ArrayBuffer to a blob, and you're done
   //var bb = new BlobBuilder();
   //bb.append(ab);
   //return bb.getBlob(mimeString);

   //New Code
   return new Blob([ab], {
      type: mimeString
   });

}

Then just append the blob to a new FormData object and post it to your server using ajax:

var blob = dataURItoBlob(someDataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();

fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);
load more v
72%

A data URI is a base64 encoded string that represents a file (i.e., instead of specifying the URL of the file, you can insert the content of the file in a webpage). When a browser encounters a URI, it decodes and constructs the original file. DataURIs are most commonly used on the web for images. When a webpage wants a file from another webpage, the URI of the file can be conveniently shared by the FormData object which can take the URI as a (key, value) pair and sends it using XMLHttpRequest.,Example: Suppose there is a DataURI for an image of type ‘gif’.Input: URI for an image.Program:,How to save an HTML 5 Canvas as an image on the server ?,How to create an image element dynamically using JavaScript ?

Example:

Input: 1. DataURI
for a file.
2. fileName. // To store the file
Output: fileName - [ObjectFile]
load more v
65%

Explain in detail the common deadlock situations in golang concurrent operations , Explain the file operation methods in Python ,HTML content details of HTML Foundation ,xdsnet on Answer for Find the position of a number in a sequence

1
/**
2 * convert dataurl to file
3 * @ param {string} dataurl - dataurl address
4 * @ param {string} file name - file name
5 */
6 dataURLtoFile(dataUrl, fileName) {
   7
   var arr = dataUrl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      8 bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
   9
   while (n--) {
      10 u8arr[n] = bstr.charCodeAt(n);
      11
   }
   12
   return new File([u8arr], fileName, {
      type: mime
   });
   13
}
load more v
75%

instanceOfFileReader.readAsDataURL(blob);
load more v
40%

We use FileReader to convert the file object to a dataUR this is done by using the readAsDataURL method.,Sometimes we just want to use an File object as an image source. But how to add the file object to the <img> src attribute?,We need to make sure to revoke the URL if we no longer need the file. If we don’t this causes memory leaks.,Converting JavaScript file objects or blobs to Base64 strings can be useful. For example when we can only send string based data to the server. In this tutorial we’ll explore how to use JavaScript to generate a Base64 string and a DataURL from a file object.

We use FileReader to convert the file object to a dataUR this is done by using the readAsDataURL method.

<input type="file" />

<script>
  // get a reference to the file input
  const fileInput = document.querySelector("input");

  // listen for the change event so we can capture the file
  fileInput.addEventListener("change", (e) => {
    // get a reference to the file
    const file = e.target.files[0];

    // encode the file using the FileReader API
    const reader = new FileReader();
    reader.onloadend = () => {
      // log to console
      // logs data:<type>;base64,wL2dvYWwgbW9yZ...
      console.log(reader.result);
    };
    reader.readAsDataURL(file);
  });
</script>
load more v
22%

Nice gist, but I am having errors at uploadAttachment() method, uploadAttachment is not defined. Where is this method at and what's inside it?

uploadAttachment()
load more v
60%

Many time we need to covert dataurl back to original file. Like dataurl of text file or zip file back to text file and zip file. IN nodejs we can do this without any external node module., The ternary conditional operator in Python

Example:

var fs = require('fs');
var dataurl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var regex = /^data:.+\/(.+);base64,(.*)$/;
var matches = string.match(regex);
var ext = matches[1];
var data = matches[2];
var buffer = Buffer.from(data, 'base64');
fs.writeFileSync('data.' + ext, buffer);

Other "convert-object" queries related to "How to convert dataURL to file object in javascript?"