欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue.js實(shí)現(xiàn)文件上傳壓縮優(yōu)化處理技巧

 更新時(shí)間:2022年11月26日 15:46:33   作者:船長(zhǎng)在船上  
這篇文章主要介紹了Vue.js實(shí)現(xiàn)文件上傳壓縮優(yōu)化處理,本文給大家介紹兩種方法一種是借助canvas的封裝的文件壓縮上傳,二是使用compressorjs第三方插件實(shí)現(xiàn),本文給大家介紹的非常詳細(xì)需要的朋友可以參考下

vue js實(shí)現(xiàn)文件上傳壓縮優(yōu)化處理

兩種方法 :

  • 第1種是借助canvas的封裝的文件壓縮上傳
  • 第2種(擴(kuò)展方法)使用compressorjs第三方插件實(shí)現(xiàn)

下面來(lái)詳細(xì)介紹兩種方法:

 借助canvas的封裝的文件壓縮上傳

封裝之前,先要對(duì)canvas相關(guān)的方法有所了解 

<canvas>簡(jiǎn)單實(shí)例如下:

<canvas id="myCanvas" width="200" height="100"></canvas>

注意: 標(biāo)簽通常需要指定一個(gè)id屬性 (或者其他), width 和 height 屬性定義的畫布的大小.

使用 style 屬性來(lái)添加邊框:

<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>

1.新建imgUpload.js

 將base64轉(zhuǎn)換為file文件

const dataURLtoFile = (dataurl, filename) => { 
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, { type: mime })
};

使用canvas的方法實(shí)現(xiàn)(拓展)

drawImage() 方法在畫布上繪制畫布。

在畫布上定位圖像:

context.drawImage(img,x,y);

在畫布上定位圖像,并規(guī)定圖像的寬度和高度:剪切圖像,并在畫布上定位被剪切的部分:

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

canvas的toDataURL()方法是返回一個(gè)包含圖片展示的 數(shù)據(jù)URL??梢允褂胻ype 參數(shù)其類型,默認(rèn)為 png 格式 

canvas.toDataURL(type, option);

option表示0到1之間的取值,選定圖片的質(zhì)量,默認(rèn)值是0.92 

const imgZip = (file) => {
    let imgZipStatus = new Promise((resolve, reject) => {
        let canvas = document.createElement("canvas"); // 創(chuàng)建Canvas對(duì)象(畫布)
        let context = canvas.getContext("2d");
        let img = new Image();
        img.src = file.content; // 指定圖片的DataURL(圖片的base64編碼數(shù)據(jù))
        var Orientation = '';
        img.onload = () => {
            // canvas.width = 400;
            // canvas.height = 300;
            canvas.width = img.width;
            canvas.height = img.height;
            context.drawImage(img, 0, 0, canvas.width, canvas.height);         
            file.content = canvas.toDataURL(file.file.type, 0.5); // 0.92為默認(rèn)壓縮質(zhì)量
            
            let files = dataURLtoFile(file.content, file.file.name);
            resolve(files)
        }
    })
    return imgZipStatus;
};

導(dǎo)出方法imgZip

export {
    imgZip
}

2.全局引入封裝的方法

main.js

// 引入imgUpload方法
import * as imgUpload from "./utils/imgUpload"
Vue.prototype.$imgUpload = imgUpload;

3.頁(yè)面中使用

這里使用了vant ui框架,實(shí)現(xiàn)的頭像上傳,如果用原生的input file方法也是一樣的使用方式

<van-uploader :after-read="afterCard" :before-read="beforeRead" accept="image/*" class="arrart"
                :max-size="10240 * 1024" @oversize="onOversize" ref="uploadFile">
                <!-- <div class="loadingWrap" v-show="personCardloading">
                  <van-loading class="colorCom uploadText" color="#fff" size="24px">{{uploadText}}</van-loading>
                </div> -->
                <van-image class="iconImg" round :src="Personal.iconUrl?$baseImgUrl+Personal.iconUrl:require('../../assets/img/touciang.png')" width="64" height="64" />
              </van-uploader>

限制上傳數(shù)量

通過(guò) max-count 屬性可以限制上傳文件的數(shù)量,上傳數(shù)量達(dá)到限制后,會(huì)自動(dòng)隱藏上傳區(qū)域。

禁用文件上傳

通過(guò) disabled 屬性禁用文件上傳。

<van-uploader disabled />

 限制上傳大小圖片

// 限制上傳大小圖片
    onOversize(file) {
      console.log(file, "file");
      this.$toast("文件大小不能超過(guò) 10M");
    },

上傳之前的圖片驗(yàn)證 

    // 上傳之前的圖片驗(yàn)證
    beforeRead(file) {
      console.log(file, "file,123");
      if (this.$utils.isImage(file.name)) {
        return true;
      } else {
        this.$toast("請(qǐng)上傳圖片格式");
      }
    },

afterCard方法,當(dāng)提交了頭像,先進(jìn)行壓縮處理,再去把formData文件流 作為參數(shù)調(diào)用接口,

獲取到后臺(tái)返回的圖片路徑,再調(diào)用更新頭像接口,把獲取的數(shù)據(jù)賦值顯示頭像的img.

// 頭像上傳
    afterCard(file) {
      this.$imgUpload.imgZip(file).then(resData => {
        const formData = new FormData();
        formData.append("file", resData);
        // 請(qǐng)求接口上傳圖片到服務(wù)器
        uploadImg(formData).then(res => {
          console.log(res, "圖片上傳");
          if (res.code == 200) {
            console.log(res.data,"res.data")
            let params = {
              bbsIconUrl: res.data,
              userId: this.id
            };
            compileUserInfo(params)
              .then(resImg => {
                console.log(resImg, "resImg");
                if (resImg.code == 200) {
                  this.Personal.iconUrl =res.data;
                  
                  this.$toast("頭像修改成功");
                } else {
                  this.$toast(resImg.msg);
                }
              })
              .catch(error => {});
          } else {
            this.$toast(res.msg);
          }
        });
      });
    },

 如果這里使用原生的input file,可按照如下操作

示例:

<input type="file" id="file" accept="image/*"> 
import axios from 'axios';
 
document.getElementById('file').addEventListener('change', (e) => {
  const file = e.target.files[0];
 
  if (!file) {
    return;
  }
  this.$imgUpload.imgZip(file).then(resData => {
        const formData = new FormData();
        formData.append("file", resData);
 
        //接口調(diào)用
        axios.post('/upload', formData).then((res) => {
            console.log('Upload success');
        });
  })
 
});

 使用compressorjs第三方插件實(shí)現(xiàn)

compressorjs 是一個(gè)開源的圖片處理庫(kù),提供了圖片壓縮、圖片旋轉(zhuǎn)等能力

語(yǔ)法:

new Compressor(file[, options]) 

1.compressorjs安裝

npm install compressorjs --save

2.方法封裝

ImageCompressor.js

quality:quality || 0.6, //壓縮質(zhì)量,圖片壓縮比 0-1

import Compressor from 'compressorjs';
export default function ImageCompressor(file, backType, quality) {
    return new Promise((resolve, reject) => {
        new Compressor(file, {
			quality:quality || 0.6, //壓縮質(zhì)量
			success(result) {
                if (!backType || backType == 'blob') {
                    resolve(result)
                } else if (backType == 'file') {
                    resolve(file)
                } else {
                    resolve(file)
                }
				// resolve(result);
			},
			error(err) {
                console.log("圖片壓縮失敗");
				reject(err);
			}
		})
    })
}

 此插件還能解決ios移動(dòng)端拍照?qǐng)D片翻轉(zhuǎn)90度問(wèn)題

3.頁(yè)面使用

import ImageCompressor from '@/utils/ImageCompressor'

4.頭像上傳處理

這里記得使用 async await,注意使用的file取值,與第一種的方法有所不同

 // 頭像上傳
    async afterCard(file) {
        let newFile = await ImageCompressor(file.file, 'file', 0.6); //圖片壓縮
        const formData = new FormData();
        formData.append("file", newFile);
        uploadImg(formData).then(res => {
          if (res.code == 200) {
            this.centerInfo.iconUrl = res.data;
            let params = {
              iconUrl: res.data,
              id: this.id,
              loginType: this.loginType
            };
            updateMineIconUrl(params)
              .then(resImg => {
                console.log(resImg, "resImg");
                if (resImg.code == 200) {
               
                  this.$toast("頭像修改成功");
                } else {
                  this.$toast(res.msg);
                }
              })
              .catch(error => {});
          } else {
            this.$toast(res.msg);
          }
        });
    
    },

如果這里使用原生的input file,可按照如下操作

示例:

<input type="file" id="file" accept="image/*"> 
import axios from 'axios';
import Compressor from 'compressorjs';
 
document.getElementById('file').addEventListener('change', (e) => {
  const file = e.target.files[0];
 
  if (!file) {
    return;
  }
 
  new Compressor(file, {
    quality: 0.6,
 
    success(result) {
      const formData = new FormData();
 
      formData.append('file', result, result.name);
        //接口調(diào)用
      axios.post('/upload', formData).then(() => {
        console.log('Upload success');
      });
    },
    error(err) {
      console.log(err.message);
    },
  });
  
});

到此這篇關(guān)于Vue.js實(shí)現(xiàn)文件上傳壓縮優(yōu)化處理的文章就介紹到這了,更多相關(guān)vue文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何在Vue3中使用視頻庫(kù)Video.js實(shí)現(xiàn)視頻播放功能

    如何在Vue3中使用視頻庫(kù)Video.js實(shí)現(xiàn)視頻播放功能

    在Vue3項(xiàng)目中集成Video.js庫(kù),可以創(chuàng)建強(qiáng)大的視頻播放功能,這篇文章主要介紹了如何在Vue3中使用視頻庫(kù)Video.js實(shí)現(xiàn)視頻播放功能,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-09-09
  • 最新評(píng)論