Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptHow to Convert Data URI to File then append to FormData?

How to Convert Data URI to File then append to FormData?

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:

Input: 1. DataURI for a file.
       2. fileName. // To store the file
Output: fileName - [ObjectFile]

Procedure: This process can be completed in 3 steps.

  • Step 1: DataURI is taken as the input.URI can be directly given as the input or it can be obtained using the function canvas.toDataURL(type[optional],value for image quality 0 to 1[optional]) in case of canvas object.
  • Step 2: DataURI is converted into a Blob(Binary Large Object-Stores any kind of data in binary format such as images, audio, and video)object file.
  • Step 3: Blob object file is appended in FormData object instance {key : value}.

Example: Suppose there is a DataURI for an image of type ‘gif’.
Input: URI for an image.
Program:




<script type="text/javascript">
    var inputURL ="";
  
    var blobObject = blobCreationFromURL(inputURL);
  
    // Create Blob file from URL
    function blobCreationFromURL(inputURI) {
  
        var binaryVal;
  
        // mime extension extraction
        var inputMIME = inputURI.split(',')[0].split(':')[1].split(';')[0];
  
        // Extract remaining part of URL and convert it to binary value
        if (inputURI.split(',')[0].indexOf('base64') >= 0)
            binaryVal = atob(inputURI.split(',')[1]);
  
        // Decoding of base64 encoded string
        else
            binaryVal = unescape(inputURI.split(',')[1]);
  
        // Computation of new string in which hexadecimal
        // escape sequences are replaced by the character 
        // it represents
  
        // Store the bytes of the string to a typed array
        var blobArray = [];
        for (var index = 0; index < binaryVal.length; index++) {
            blobArray.push(binaryVal.charCodeAt(index));
        }
  
        return new Blob([blobArray], {
            type: inputMIME
        });
    }
  
    var fdataobj = new FormData();
  
    // Create formdata object and append the object
    // file to the name 'Blob file'
    fdataobj.append("Blob File", blobObject);
  
    // FormData object content is displayed in alert box.
    for (var pair of fdataobj.entries()) {
        alert('neveropen\n' + pair[0] + '–' + pair[1])
    }
</script>


Output: The output of the FormData object will be displayed in the alert box as a name and ‘object file’ value pair. The object file can be read using the FileReader object of JavaScript which will read the object file and can be displayed using any of the JavaScript display techniques.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments