0

I trying to take image as a file input from the user and the display it as a base64 encoded string. Here's my code

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript – Convert Image to Base64 String</title>
</head>
<body>

    <input type="file" name="upload" id="file" accept="image/*">
    <br>
    <br>    
    <button type="button" onclick="showResult()">Show Source</button>
    <div id="image-source">Image Source :</div>
    <br>
    <div>Data URL:</div>
    <div id="result"></div>
    <script type="text/javascript">
        function toDataURL(src, callback) {
            var xhttp = new XMLHttpRequest();

            xhttp.onload = function() {
                var fileReader = new FileReader();
                fileReader.onloadend = function() {
                    callback(fileReader.result);
                }
                fileReader.readAsDataURL(xhttp.response);
            };

            xhttp.responseType = 'blob';
            xhttp.open('GET', src, true);
            xhttp.send();
        }



        showResult(){
            var x = document.getElementById("file").value;
            document.getElementById("image-source").innerHTML = x;
            toDataURL(x, function(dataURL) {
            // do something with dataURL
            document.getElementById('result').innerHTML = dataURL;
        });
        }


    </script>

</body>
</html>

Do I need to store the source of the image seperately to encode it ? Is there a simpler way to encode a user uploaded image ??

6
  • Why do you want to mess with base64!? A waste of CPU, 33% extra storage, and headaches for usually no benefit. Commented Feb 27, 2020 at 6:00
  • Hi @Brad actually I am trying to send the image to vision api, the api accepts either base-encoded files or gcloud bucket file links or image url (public), I want the results dynamically so I thought base encoding would be best. If know any better method I'd be more than glad to use it . Commented Feb 27, 2020 at 6:04
  • Wow, what sort of API won't accept binary image data? That'd be far better. Commented Feb 27, 2020 at 6:04
  • According to the documentation cloud.google.com/vision/docs/request#providing_the_image , these are only listed ways. I am new to programming, any guidance would be helpful. Commented Feb 27, 2020 at 6:11
  • Do you want to convert an image a user has selected (using the file input element) to a base64 dataURL on the client side? I'm not understanding why the code is using XMLHttpRequest and what its purpose is. Commented Feb 27, 2020 at 6:35

1 Answer 1

4

Here's a simple example converting the first image selected using the file browse button. File reading occurs on the client side after an image has been selected. File reading is asynchronous so I've promisified the file reading function:

"use strict";

const fileDataURL = file => new Promise((resolve,reject) => {
    let fr = new FileReader();
    fr.onload = () => resolve( fr.result);
    fr.onerror = reject;
    fr.readAsDataURL( file)
});

function showResult(file) {
    fileDataURL( file)
    .then( data => (document.getElementById("result").textContent = data))
    .catch(err => console.log(err));
}
#result {
   width: 80%;
   font-family: monospace;
   overflow-wrap: break-word;
}
<p>
<input type="file" onchange="showResult( this.files[0]);" accept="image/*">
<div>Data URL:</div>
<div id="result"></div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.