vue+node实现图片上传及预览的示例方法

2020-06-12 21:17:33易采站长站整理

multiple accept="image/*">
</div>

通过@change=”change”监听图片的上传,把图片转成base64后(后面会讲怎么转base64)将base64的地址加入到images数组,通过v-for=”(image,index) in images”把要上传的图片在页面中显示出来,即达到了预览的效果

js部分

data部分


data() {
return {
content: '',//分享动态的文字内容
maxSize: 10240000 / 2,//图片的最大大小
maxCount: 8,//最大数量
filesArr: [],//保存要上传图片的数组
images: []//转成base64后的图片的数组
}
}

delete方法


deleteimg(index) {
this.filesArr.splice(index, 1);
this.images.splice(index, 1);
}

change方法


change(e) {
let files = e.target.files;
// 如果没有选中文件,直接返回
if (files.length === 0) {
return;
}
if (this.images.length + files.length > this.maxCount) {
Toast('最多只能上传' + this.maxCount + '张图片!');
return;
}
let reader;
let file;
let images = this.images;
for (let i = 0; i < files.length; i++) {
file = files[i];
this.filesArr.push(file);
reader = new FileReader();
if (file.size > self.maxSize) {
Toast('图片太大,不允许上传!');
continue;
}
reader.onload = (e) => {
let img = new Image();
img.onload = function () {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let w = img.width;
let h = img.height;
// 设置 canvas 的宽度和高度
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
let base64 = canvas.toDataURL('image/png');
images.push(base64);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
}

put方法把filesArr中保存的图片通过axios发送到后端,注意要设置headers信息


put() {
Indicator.open('发布中...');
let self = this;
let content = this.content;
let param = new FormData();
param.append('content', content);
param.append('username', this.userInfo._id);
this.filesArr.forEach((file) => {
param.append('file2', file);
});
self.axios.post('/upload/uploadFile', param, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function (result) {
console.log(result.data);