項目快上線了。測試小姐姐忽然找我,提出ios手機豎拍的照片會在pc上顯示會逆時針旋轉90度。javascript
項目中使用element upload實現上傳,在此記錄下解決的方法。java
<el-upload ref="uploadSgs" :action="this.baseServerUrl+'/fileUpload/uploadPic?filepath=designFile'" :on-success="handleSgsSuccess" :on-preview="handleSgsPreview" :beforeUpload="beforeAvatarUpload"> <el-button size="small" type="primary"></el-button>
</el-upload>
在:beforeUpload 中對上傳的圖片進行處理。ios
beforeAvatarUpload(file) {
//校驗圖片最大上傳10M var testmsg=file.name.substring(file.name.lastIndexOf('.')+1); const isLt2M = file.size / 1024 / 1024 < 10; if(!isLt2M) { this.$message({ message: '上傳文件大小不能超過 10MB!', type: 'warning' }); return isLt2M; }else {
//這裏beforeUpload方法能夠返回一個Promise,咱們能夠經過resolve將處理事後的文件上傳; return new Promise((resolve) => { fileUtil.getOrientation(file).then((orient) => { if (orient && orient === 6) { let reader = new FileReader() let img = new Image() reader.onload = (e) => { img.src = e.target.result img.onload = function () { const data = fileUtil.rotateImage(img, img.width, img.height) const newFile = fileUtil.dataURLtoFile(data, file.name) resolve(newFile) } } reader.readAsDataURL(file) } else { resolve(file) } }) }) }
}
這裏須要安裝exif插件npm
npm install exif-js --savecanvas
exif的使用方法看這裏:http://code.ciaoca.com/javascript/exif-js/測試
使用到的方法:網站
import EXIF from 'exif-js'
export default {
getOrientation: (file) => {
return new Promise((resolve) => {
EXIF.getData(file, function () {
const orient = EXIF.getTag(this, 'Orientation')
resolve(orient)
})
})
},
dataURLtoFile: (dataurl, filename) => {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const 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});
},
rotateImage: (image, width, height) => {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
ctx.save()
canvas.width = height
canvas.height = width
ctx.rotate(90 * Math.PI / 180)
ctx.drawImage(image, 0, -height)
ctx.restore()
return canvas.toDataURL("image/jpeg")
},
}
其餘方法:this
handlePictureDetailPreview(file) {
console.log(file)
const _self = this;
this.dialogProcessImageUrl = file.url;
this.dialogProcessVisible = true;
},
handleDetailRemove(file, fileList){
const _self = this;
_self.imageDetaillist.pop();
},
handleDetailSuccess(res,file) {
console.log(file)
console.log(res)
const _self = this;
let imgList={};
let lastindex = res.obj.lastIndexOf('/');
imgList.name=res.obj.substr(lastindex+1);
imgList.url=urlConfig.imgServerUrl+res.obj;
_self.imageDetaillist.push(imgList);
_self.formImageDetail.image=res.obj;
},
參考網站:https://blog.csdn.net/qq_23158083/article/details/82835357;url