这是原生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);
};
};
});
}
网友评论