html部分:
<van-button
round
type="danger"
size="large"
@click="phone"
>拍摄</van-button
>
<input
ref="phone"
type="file"
accept="image/*"
style="display: none"
@change="selectPhone($event)"
/>
js部分:
methods: {
phone() {
this.$refs.phone.click();
},
// 上传照片
upload(userFile) {
let file = this.base64ToFile(
userFile,
new Date().getTime() + '.png'
);
// 使用自定义的请求方法哈,每个项目封装的是不一样的
this.getRequest(
`${requestUrl}`,
{
method: 'post',
data: {
image: file,
},
},
// 请求头类型一般是需要修改的
{ headers: { 'Content-Type': 'multipart/form-data' } }
)
.then((res) => {
if (res && res.resultCode == '000000') {
//上传成功后的操作
} else {
//上传失败后的操作
}
});
},
async selectPhone(el) {
var file = el.target.files[0];
let img = await this.readImg(file);// 读取上传的照片并转为base64
let image = await this.compressImg(img, file.type, 1000, 1000);//防止上传的照片过大,进行压缩处理
if (image) {
// 开始上传
this.upload(image);
}
},
/**
* 压缩图片
* @param img 被压缩的img对象
* @param type 压缩后转换的文件类型
* @param mx 触发压缩的图片最大宽度限制
* @param mh 触发压缩的图片最大高度限制
*/
compressImg(img, type, mx, mh) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const { width: originWidth, height: originHeight } = img;
// 最大尺寸限制
const maxWidth = mx;
const maxHeight = mh;
// 目标尺寸
var targetWidth = originWidth;
var targetHeight = originHeight;
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > 1) {
// 宽图片
targetWidth = maxWidth;
targetHeight = Math.round(
maxWidth * (originHeight / originWidth)
);
} else {
// 高图片
targetHeight = maxHeight;
targetWidth = Math.round(
maxHeight * (originWidth / originHeight)
);
}
}
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(0, 0, targetWidth, targetHeight);
// 图片绘制
context.drawImage(img, 0, 0, targetWidth, targetHeight);
resolve(canvas.toDataURL(type, 0.2));
});
},
readImg(file) {
const _this = this;
return new Promise((resolve, reject) => {
const img = new Image();
const reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
let bold = _this.base64ToFile(
img.src,
new Date().getTime() + '.png'
);
};
reader.onerror = function (e) {
reject(e);
};
reader.readAsDataURL(file);
img.onload = function () {
resolve(img);
};
img.onerror = function (e) {
reject(e);
};
});
},
base64ToFile(urlData, fileName) {
let arr = urlData.split(',');
let mine = arr[0].match(/:(.*?);/)[1];
let bytes = atob(arr[1]); //解码base64
let n = bytes.length;
let ia = new Uint8Array(n);
while (n--) {
ia[n] = bytes.charCodeAt(n);
}
return new File([ia], fileName, { type: mine });
},
},