[英]Convert image to base64 without server
I'm using the Pinterest Javascript SDK to try and create a pin. 我正在使用Pinterest Javascript SDK尝试创建图钉。 The parameters to set the image is 1 of either;
设置图像的参数之一。
image
- Upload the image you want to pin using multipart form data image
-使用多部分表单数据上传您要固定的图片
image_url
- The link to the image that you want to Pin, or image_url
要固定的图像的链接,或者
image_base64
- The link of a Base64 encoded image image_base64
-Base64编码图像的链接
I'm trying to create the Pin from the client side, without going through a server. 我正在尝试从客户端创建Pin,而无需通过服务器。 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). 我已经尝试过使用
image
和image_url
参数来发送该值( imageUrl
),但是由于该值解析为硬盘驱动器上的某个位置,因此无法正常工作(可能是预期的)。
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. 因此,现在我必须尝试找出如何使用
image_base64
选项,这意味着我需要在用户计算机上将图像转换为base64。
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 还是更好,如果有人知道如何使用
image
参数,那我认为会更好
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 可以使用
change
附加到事件<input type="file">
元素, FileReader
转换File
对象在<input type="file">
元件.files
属性到一个data URI
或base64
的部分data URI
内change
事件处理程序
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.