上傳圖片太大,需要前台進行圖片壓縮
上傳圖片大於100* 1024 的用canvas 來壓縮來解決
然后IOS拍照上傳會有圖片旋轉的問題,然后用了github 上的exif.js很好的插件,項目里面npm install exif-js --save 安裝,
然后import一下就可以使用了
html
<div class="operate">
<span class="btn" @click="sendMsg" v-if="isSend&&isCanSend">{{btndesc}}</span>
<span class="btn" v-if="isSend&&!isCanSend">{{btndesc}}</span>
<label class="choosepic" v-if="!isSend&&!isCanUpload"></label>
<label class="choosepic" for="uploadcolor" v-if="!isSend&&isCanUpload"></label>
<input class="fileupload" type="file" accept="image/*" id="uploadcolor" @change="upload">
</div>
js
import Exif from 'exif-js'
export default {
data () {
return {
headerImage:'',picValue:''
}
},
mounted () {
},
methods: {
upload (e) {
let _this = this;
console.log('change----------->',e);
_this.resulting = [];
let files = e.target.files || e.dataTransfer.files;
// let length = files.length;
let timer = setTimeout(()=>{
_this.$loading.show({
text: '發送中'
})
clearTimeout(timer);
},500);
_this.singleUpload(files[0],0,1);
_this.isCanUpload = false;
e.target.value = null;
},
singleUpload(files,i,length){
this.files = files;
this.name = this.files.name;
this.picValue = files;
this.imgPreview(this.picValue,i,length);
console.log(this.picValue);
},
imgPreview (file,i,length) {
let self = this;
let Orientation;
// this.$emit('dealupload');
//去獲取拍照時的信息,解決拍出來的照片旋轉問題
EXIF.getData(file, function(){
Orientation = EXIF.getTag(this, 'Orientation');
});
// 看支持不支持FileReader
if (!file || !window.FileReader) {
self.$loading.hide();
return;
}
if (sAser.storage('deviceOS')==2){ //安卓,sAser.storage('deviceOS')==2
self.checkHash(file,i,length);
}
else{ //ios sAser.storage('deviceOS')==1
if (/^image/.test(file.type)) {
// 創建一個reader
let reader = new FileReader();
// 將圖片2將轉成 base64 格式
reader.readAsDataURL(file);
// 讀取成功后的回調
reader.onload = function () {
let result = this.result;
let img = new Image();
img.src = result;
img.onload = function () {
let data = self.compressImage(img,Orientation,file);
self.headerImage = data;
let fileCompress = self.convertBase64UrlToBlob(data);
self.checkHash(fileCompress,i,length);
}
}
}
}
},
rotateImg (img, direction, canvas, lastRotate) {
//最小與最大旋轉方向,圖片旋轉4次后回到原方向
const min_step = 0;
const max_step = 3;
if (img == null)return;
//img的高度和寬度不能在img元素隱藏后獲取,否則會出錯
let height = 0;
let width = 0;
if(lastRotate == true){
height = canvas.height;
width = canvas.width;
}else{
height = img.height;
width = img.width;
}
let step = 2;
if (step == null) {
step = min_step;
}
if (direction == 'right') {
step++;
//旋轉到原位置,即超過最大值
step > max_step && (step = min_step);
} else {
step--;
step < min_step && (step = max_step);
}
//旋轉角度以弧度值為參數
let degree = step * 90 * Math.PI / 180;
let ctx = canvas.getContext('2d');
switch (step) {
case 0:
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
break;
case 1:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, 0, -height, width, height);
break;
case 2:
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height, width, height);
break;
case 3:
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, 0, width, height);
break;
}
},
//圖片壓縮
compressImage(img, Orientation,file) {
let size = file.size;
let initSize = img.src.length;
let maxWidth = 1600;
let w = img.width;
let h = img.height;
console.log('原始 寬度:' + w + ",高度:" + h);
if(w > maxWidth){
//如果圖片寬度大於1600px,則將圖片進行等比縮放
let hRatio = maxWidth / w;
w = maxWidth;
h = h * hRatio;
console.log('高度縮放比例:' + hRatio +'縮放后 寬度:' + w + ",高度:" + h);
}
//創建一個image對象,給canvas繪制使用
let cvs = document.createElement('canvas');
cvs.width = w;
cvs.height = h;
let ctx = cvs.getContext('2d');
// this.getToast("旋轉:" + Orientation, "20em", "22em");
//修復ios上傳圖片的時候 被旋轉的問題
if(Orientation != "" && Orientation != 1){
switch(Orientation){
case 6://需要順時針(向左)90度旋轉
// ctx.rotate(Math.PI / 2);
// ctx.drawImage(img, 0, -h, w, h);
//上面的方式處理有問題,使用rotateImg方法。其他不能使用rotateImg方法,會有問題
this.rotateImg(img,'left',cvs, true);
break;
case 8://需要逆時針(向右)90度旋轉
ctx.rotate(3 * Math.PI / 2);
ctx.drawImage(img, -w, 0, w, h);
break;
case 3://需要180度旋轉
ctx.rotate(Math.PI);
ctx.drawImage(img, -w, -h, w, h);
break;
default:
ctx.drawImage(img, 0, 0, w, h);
console.log('特殊情況1111111111==========================>',ctx);
break;
}
}else{
console.log('特殊情況2222222222222==========================>',ctx);
ctx.drawImage(img, 0, 0, w, h);
}
//進行最小壓縮
let rate = 0.3;
if (size<1048576){
rate = 1;
}
console.log('==============fileing===============>',file.size,rate);
let ndata = cvs.toDataURL('image/jpeg', 0.3);
console.log('壓縮后內容:' + ndata);
console.log('壓縮前:' + initSize);
console.log('壓縮后:' + ndata.length);
console.log('壓縮率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
return ndata;
},
convertBase64UrlToBlob(urlData) {
//將以base64的圖片url數據轉換為Blob
var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime});
},
calcHash(file){
return sha1File(file);
},
postImg (file,i,length) {
//這里寫接口
let _this = this;
let name = _this.name;
let data = {};
// this.$emit('uploading');
// let files = this.files;
let files = file;
let param = new FormData(); //創建form對象
if(files!=''){
param.append('file', files,files.name); //單個圖片 ,多個用循環 append 添加
}else{
// this.$message.error('請添加圖片');
}
// param.append('param', JSON.stringify(data));//添加form表單中其他數據
let config = {
headers:{'Content-Type':'multipart/form-data'}
}; //添加請求頭
this.$http.post(_this.ajaxUrl,param,config)
.then(response=>{
//上傳成功后,檢查上傳后的圖片是否有效
console.log('返回結果',response);
_this.uploadState(response,i,length);
}).catch(err=>{
_this.uploadFail();
console.log('接口失敗返回結果',err);
})
},
uploadFail(){
//發送圖片過程中出現失敗的處理
let _this = this;
_this.isCanUpload = true;
_this.$loading.hide();
},
}
}