将图像转换为base64而不需要服务器
问题描述:
我正在使用Pinterest Javascript SDK尝试创建一个图钉。设置图像的参数是1;将图像转换为base64而不需要服务器
image
- 将图像上传你想使用多形式的数据
image_url
引脚 - 链接到要固定图像,或
image_base64
- Base64编码的图像的链接
我正在尝试从客户端创建Pin,而无需通过服务器。我的形式很简单:
<div class="file-upload">
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
和我读到使用
const imageUrl = document.getElementById('fileToUpload').value;
我已经试用过image
和image_url
参数发送通过值(imageUrl
)的的那个值,但由于价值做出决议到我硬盘上的某个地方,它不起作用(可能是预期的)。
所以现在我必须尝试弄清楚如何使用image_base64
选项,这意味着我需要将图像转换为用户计算机上的base64。
我该怎么做呢?或者更好的是,如果有人知道我怎么可以使用image
参数,我认为这将是更好的
答
您可以使用连接到<input type="file">
元素,FileReader
到File
对象转换为<input type="file">
元素.files
财产change
事件到data URI
或内change
事件处理程序的data URI
base64
部
<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>
[CONVERT Image url to Base64]可能重复(https://stackoverflow.com/questions/22172604/convert-image-url-to-base64) – Tor