我需要将我的图像转换为Base64字符串,这样我就可以将我的图像发送到服务器。
有JavaScript文件吗?否则,我如何转换它?
我需要将我的图像转换为Base64字符串,这样我就可以将我的图像发送到服务器。
有JavaScript文件吗?否则,我如何转换它?
当前回答
document.querySelector(“输入”)。Onchange = e => { const fr = new FileReader() Fr.onloadend = () => document.write(fr.result) fr.readAsDataURL (e.target.files [0]) } < input type = " file " >
其他回答
您可以使用FileAPI,但它几乎不受支持。
你可以使用HTML5 <canvas>:
创建一个画布,将图像加载到其中,然后使用toDataURL()来获得Base64表示(实际上,它是一个data: URL,但它包含Base64编码的图像)。
假设您在浏览器中执行此操作:
等待:
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' });
return window.URL.createObjectURL(response.data);
与承诺
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' })
.then((response) => {
const dataUrl = window.URL.createObjectURL(response.data);
// do something with your url
});
document.querySelector(“输入”)。Onchange = e => { const fr = new FileReader() Fr.onloadend = () => document.write(fr.result) fr.readAsDataURL (e.target.files [0]) } < input type = " file " >
据我所知,图像可以通过FileReader()转换为Base64字符串,也可以将其存储在canvas元素中,然后使用toDataURL()获取图像。我也遇到过类似的问题你可以参考这个。
将图像转换为已经加载的画布