html5 <input type='file' > 上傳本地文件/圖片并壓縮

這是原生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);
      };
    };
  });
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容