使用elementUI中 Upload 上传组件
<el-upload
action
list-type="picture-card"
:on-preview="handlePictureCardPreview"
ref="upload"
:auto-upload="false"
:on-change="fileChange"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt>
</el-dialog>
首先,将自动上传关闭—auto-upload,添加on-change属性,该属性为选择图片时调用的方法
fileChange(file) {
const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg'];
const isJPG = typeArr.indexOf(file.raw.type) !== -1;
// image/png, image/jpeg, image/gif, image/jpg
const isLt3M = file.size / 1024 / 1024 < 3;
if (!isJPG) {
this.$message.error('只能是图片!');
this.$refs.upload.clearFiles();
this.files = null;
return;
}
if (!isLt3M) {
this.$message.error('上传图片大小不能超过 3MB!');
this.$refs.upload.clearFiles();
this.files = null;
return;
}
this.files = file.raw;
console.log(file);
}
首先可以在该方法中判断上传的文件大小以及文件类型,主要为获取file信息,
console中file信息为
上传图片在原生input type=file 中,上传为raw中的内容。
此时将该内容保存下来。
请求头我设置为'Content-Type': 'multipart/form-data'
然后使用FormData对象封装参数
const formData = new FormData();
Object.keys(this.InfoData).forEach((ele) => {
formData.append(ele, this.InfoData[ele]);
});
formData.append('file', this.files);
此时InfoData为其他字段,file为上传图片的字段。
这样调接口时,将formData作为参数,post传过去就可以了,这样发送的参数类型为
与后台沟通好就可以了。