<input type="file" @change="handleUpdateFIle">
我在应用程序中运行以下代码片段时遇到问题。当我尝试使用 FileReader 对象的结果设置 img 元素的 src 时,收到一条错误消息“img src 无效”。你能帮我解决这个问题吗?
const handleUpdateFIle = (e: file) => {
const file= e.target.files[0]
const reader = new FileReader()
const img = new Image()
reader.onload = () => {
const arrayBuffer = reader.result
const blob = new Blob([arrayBuffer],{type: file.type || 'image/png'})
console.log('blob',blob)
const URL = window.URL || window.webkitURL
const url = URL.createObjectURL(blob)
img.src = url
//img.src blob:http:xxx
}
reader.readAsArrayBuffer(file)
}
console tip
Uncaught (in promise) img src is not valid
我尝试使用 readAsDataURL 而不是 readAsArrayBuffer,但仍然遇到相同的错误。请问可以提供解决方案吗?
img.src = URL.createObjectURL(file)
src
* 属性接受一个 URL,这是一个
String
— 但在这里你插入了一个数组缓冲区**。你必须...
const handleUpdateFIle = (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const arrayBuffer = reader.result;
const base64String = arrayBufferToBase64(arrayBuffer); // Convert ArrayBuffer to Base64
const dataUrl = `data:${file.type || 'image/png'};base64,${base64String}`;
const img = new Image();
img.src = dataUrl;
};
reader.readAsArrayBuffer(file); // Read the file as ArrayBuffer
};
// Helper function to convert ArrayBuffer to Base64
const arrayBufferToBase64 = (buffer) => {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
};
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#src
**https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
***https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data