這是原生Input的寫法
<input
type="file"
accept="image/*"
@change="handleUploaded($event,index)"
>
function handleUploaded (event:any, index:number) {
const file = event.target.files[0]
fileToBase64(file).then((url) => {
imageUrl.value = url
})
}
/**
* 將文件轉換為base64格式的字符串,可以根據最大文件大小進行壓縮
* @param file 要轉換的文件
* @param maxSizeInKB 最大允許的文件大小(以KB為單位),默認為500KB
* @returns 返回一個Promise,最終解析出base64格式的字符串
*/
export function fileToBase64(file: File, maxSizeInKB: number = 500): Promise<string> {
return new Promise<string>((resolve) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function () {
const image = new Image();
image.src = this.result as string;
image.onload = function () {
const maxSizeInBytes = maxSizeInKB * 1024;
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
let width = image.width;
let height = image.height;
if (image.width > image.height) {
if (image.width > 1024) {
width = 1024;
height = (image.height * 1024) / image.width;
}
} else {
if (image.height > 1024) {
height = 1024;
width = (image.width * 1024) / image.height;
}
}
canvas.width = width;
canvas.height = height;
context.drawImage(image, 0, 0, width, height);
let quality = 0.7; // 初始質量為0.7
let imageData = canvas.toDataURL('image/jpeg', quality);
// 通過不斷調整質量以縮小文件大小
while (imageData.length > maxSizeInBytes && quality > 0.1) {
quality -= 0.1;
imageData = canvas.toDataURL('image/jpeg', quality);
}
resolve(imageData);
};
};
});
}