简体   繁体   中英

Convert image to base64 without server

I'm using the Pinterest Javascript SDK to try and create a pin. The parameters to set the image is 1 of either;

image - Upload the image you want to pin using multipart form data

image_url - The link to the image that you want to Pin, or

image_base64 - The link of a Base64 encoded image

I'm trying to create the Pin from the client side, without going through a server. My form is simply:

<div class="file-upload">
  <input type="file" name="fileToUpload" id="fileToUpload">
</div>

and I read the value of that using

const imageUrl = document.getElementById('fileToUpload').value;

I have tried both the image and image_url parameters to send that value ( imageUrl ) through, but because the value resolves to a place on my hard drive, it doesn't work (probably expectantly).

So now I have to try and figure out how to use the image_base64 option, which means I need to convert the image to base64 on the users machine.

How could I go about doing that? Or better yet, if someone knows how I can use the image parameter, I think that would be much better

You can use change event attached to <input type="file"> element, FileReader to convert File object at <input type="file"> element .files property to a data URI or base64 portion of data URI within change event handler

 <div class="file-upload"> <input type="file" name="fileToUpload" id="fileToUpload"> </div> <script> const input = document.getElementById("fileToUpload"); const reader = new FileReader; reader.onload = () => { const dataURL = reader.result; const base64 = reader.result.split(",").pop(); console.log(dataURL, base64); } input.onchange = () => { reader.abort(); reader.readAsDataURL(input.files[0]); } </script> 

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