vue圖片壓縮compressor.js

像我們寫(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);

? ? },

? });

},

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容