像我們寫(xiě)vue項(xiàng)目的時(shí)候上傳圖片經(jīng)常會(huì)遇到上傳圖片需要壓縮傳給后臺(tái),以免圖片過(guò)大導(dǎo)致服務(wù)器內(nèi)存崩潰。現(xiàn)在有一個(gè)很好的基于vue的圖片壓縮插件,話不多說(shuō),上代碼
首先先安裝
npm?install?image-compressor.js?
然后再到需要用到的vue組件中引入
import ImageCompressor from 'image-compressor.js'
組件中的代碼示例
<input type="file" multiple="multiple" id="file3" v-on:change="load($event)" ref="file1" />
load(e){
var token = localStorage.getItem('token')
var that = this;
const file = e.target.files[0]; // file對(duì)象
if (!file) { return } // 為空處理
? new ImageCompressor(file, {
? ? quality: .6,//圖片壓縮的質(zhì)量,可改
? ? success(result) {
? ? console.log(result)
? ? ? const formData = new FormData();?
? ? ? formData.append('userImg', result, result.name);//壓縮后的文件會(huì)自動(dòng)轉(zhuǎn)換成二進(jìn)制文件流類型
? ? ?var obj = {
? ? ? ? ? ? ? ?data: formData,
? ? ? ? ? ? ? ?isQs: true
? ? ? ? ? ?}
? 通過(guò)XMLHttpRequest服務(wù)發(fā)送壓縮的圖像文件-Send the compressed image file to server with XMLHttpRequest.
? ? ?that.$axios.post(that.$api.getUser, obj,{
? ? ? ? ? ? ? headers:{
? ? ? ? ? ? ? ?'token':token
? ? ? ? ? ? ? }
? ? ? ?}).then(res=>{
? ? ? ? ? ?});
? ? },
? ? error(e) {
? ? ? console.log(e.message);
? ? },
? });
},