1.vue-element-upload 在不调用接口的情况下实现图片上传列表的展示,预览与删除
<el-upload
ref="upload"
action="#"
:on-change="fileChange"
:limit="1"
list-type="picture-card"
:auto-upload="false"
:on-preview="handlePictureCardPreview"
:on-exceed="handleExceed"
:on-remove="handlePictureRemove"
>
<i class="el-icon-plus"></i>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且只能上传一张
</div>
</el-upload>
<!-- 图片预览弹窗 -->
<el-dialog :visible.sync="previewDialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
// 点击预览图片按钮时的回调函数
handlePictureCardPreview(file) {
console.log(file);
// console.log(this.fileList);
//把URL值赋值给预览框
this.dialogImageUrl = file.url;
this.previewDialogVisible = true;
},
// 选择文件时的回调
fileChange(file, fileList) {
console.log(file);
// console.log(fileList);
var reader = new FileReader();
var that = this;
reader.onload = function() {
that.imgUrl = reader.result;
};
reader.readAsDataURL(file.raw);
},
//以base64格式转化为blob格式,以便调用接口时使用
convertBase64UrlToBlob(base64) {
var urlData = base64;
var type = "image/png";
var bytes = window.atob(urlData.split(",")[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {
type: type
});
},
//调用接口时,文件格式要求为Content-Type:multipart/form-data;
var formData = new FormData();
formData.append(
//这里定义接口需要的文件名
"avatar",
//这里是接口所需接收的文件,转化后的图片
this.convertBase64UrlToBlob(this.imgUrl),
//这里定义图片名字的结尾
"img_" + Date.parse(new Date()) + ".png"
);
2.vue-iview-upload
//列表展示需要单独代码展示
<div
class="demo-upload-list"
v-for="(item, index) in previewImgs"
:key="index"
>
<template>
<img :src="item" />
<div class="demo-upload-list-cover">
<Icon
type="ios-eye-outline"
@click.native="handleView(item)"
></Icon>
<Icon
type="ios-trash-outline"
@click.native="handleRemove(item)"
></Icon>
</div>
</template>
</div>
//组件上传
<Upload
ref="upload"
:default-file-list="defaultList"
accept=".jpg,.jpeg,.png,.bmp"
:before-upload="handleBeforeUpload"
type="drag"
action="#"
style="display: inline-block;width:98px;"
>
<div style="width: 98px;height:98px;line-height: 98px;">
<Icon type="ios-camera" size="20"></Icon>
</div>
</Upload>
<Modal title="预览图片" v-model="visible">
<img :src="imgName" style="width: 100%" />
</Modal>
//预览函数
handleView(name) {
this.imgName = name;
this.visible = true;
},
//删除函数
handleRemove(file) {
this.previewImgs.splice(this.previewImgs.indexOf(file), 1);
console.log(this.previewImgs);
},
//上传图片之前的回调
handleBeforeUpload(file) {
// console.log(file);
var reader = new FileReader();
var that = this;
reader.readAsDataURL(file);
reader.onload = function(e) {
if (that.previewImgs.length < 5) {
that.previewImgs.push(reader.result);
} else {
that.$Message.info("最多只能上传五张照片!");
console.log(that.previewImgs);
}
};
return false; //终止上传,最后和form表单一起提交
},
data() {
return {
//预览路径
imgName: "",
//控制预览框
visible: false,
// 未调用接口时的URL
previewImgs: []
};
},