<div class="upload_bar">
<div class="upload_box">
<input
type="file"
class="load_input"
accept="image/gif, image/jpeg, image/jpg, image/png"
@change="changeImage(0,'.upload_img','pre_img','pay_image',$event)"
/>
<div class="icon_box">
<i class="iconfont iconjia1"></i>
<p class="my_gray">请选择凭证截图</p>
</div>
</div>
<div class="img_box">
<img id="upload_img" class="load_img" :src="pre_img" alt />
</div>
</div>
import { mychangeImg } from "@/lib/utils.js";
export default {
data() {
return {
// 预览的图片
pre_img: "",
// 上传的图片
uploadimg: ""
};
},
methods: {
async changeImage(ind, upclass, preupname, e) {
let res = await mychangeImg(this, ind, upclass, preupname, e,1);
this.uploadimg = res.file_path;
},
},
}
utils.js
/**
* 上传图片
* @param _this //vue实例
* @param ind // class下标
* @param upclass // 上传的class
* @param preupname // 预览的变量
* @param e // $event
*/
export const mychangeImg = (_this, ind, upclass, preupname, e,ctype) => {
return new Promise((resolve) => {
var that = _this;
var img = document.querySelectorAll(upclass);
var canvas = document.createElement("canvas");
var file = e.target.files[0];
if (file) {
var render = new FileReader();
render.readAsDataURL(file);
render.onload = function (e) {
that[preupname] = e.target.result;
img[ind].onload = function () {
var w = img[ind].naturalWidth;
var h = img[ind].naturalHeight;
let aspect = w / h;
if (w >= 720) {
w = 720
}
h = (w / aspect).toFixed(0);
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext("2d");
ctx.drawImage(img[ind], 0, 0, w, h);
var base64 = canvas.toDataURL("image/jpeg", 0.92);
var myImg = convertBase64UrlToBlob(base64);
var formData = new FormData();
formData.append("file", myImg, "image.png");
//调用接口
uploadPay(formData).then(res => {
if (res.data.code == 200) {
let _res = res.data.data;
resolve(_res)
Toast({
message: res.data.msg,
duration: 1000
});
}
});
}
}
}
})
}
/**
* base64转blob对象
* @param urlData //url地址
*/
export const convertBase64UrlToBlob = (urlData) => {
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
});
}
formData.append添加文件必须加后缀名作为第三个参数;
如有不足,请见谅,并告诉我最优解决方法,我是小白