获取文件
afterRead(file, name) {
let that =this;
file.message = "上传中...";
file.status = "uploading";
return new Promise(() => {
const fileName = file.name
const reader = new FileReader()
reader.readAsDataURL(file.file)
reader.onload = () => {
getImgUrl({
url: reader.result,
that,
cb: (base64) => {
let newForm = file;
newForm.content = base64;
this.uploadAxios(newForm, name);
}
})
}
})
},
uploadAxios(file, name) {
let formData = new FormData();
// formData.set("file", file.file);
let blob = dataURItoBlob(file.content);
formData.append("file", blob,‘image.png‘);
formData.set("fileType", 0);
formData.set("type", this.personTypeDesc || "event");
formData.set("path", "event");
formData.set("userId", localStorage.staffId);
uploadFile(formData)
.then(({ success, data }) => {
if (success) {
file.status = "success";
this.handlePicture.push(data);
} else {
file.status = "failed";
Toast({
message: "图片上传服务失败",
});
this.fileList.splice(name.index, 1);
}
})
.catch((err) => {
file.status = "failed";
file.message = "上传失败";
});
},
通过canvas添加水印
export function getImgUrl ({
url = ‘‘,
that,
imgWidth=98,
imgHight= 98,
content,
cb = null
}) {
const img = new Image()
img.src = url
img.crossOrigin = ‘anonymous‘
img.onload = function () {
const canvas = document.createElement(‘canvas‘)
canvas.width = imgWidth;
canvas.height = imgHight;
const ctx = canvas.getContext(‘2d‘)
ctx.drawImage(img, 0, 0);
ctx.fontSize="8px";
// 单独绘制水印
content = that.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
ctx.fillText(content,0,20);
const base64Url = canvas.toDataURL()
// return base64Url
cb && cb(base64Url)
}
}
将base64转化为二进制
export function dataURItoBlob(base64Data) {
var byteString;
if (base64Data.split(‘,‘)[0].indexOf(‘base64‘) >= 0)
byteString = atob(base64Data.split(‘,‘)[1]);
else
byteString = unescape(base64Data.split(‘,‘)[1]);
var mimeString = base64Data.split(‘,‘)[0].split(‘:‘)[1].split(‘;‘)[0];
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
基于vant上传图片添加水印