图片上传是用的 element ui 的 el-upload 组件
这个组件的配置可以看官方文档:Element - The world's most popular Vue UI frameworkElement - The world's most popular Vue UI frameworkElement - The world's most popular Vue UI framework
<template>
<div>
<el-upload
class="upload-demo"
ref="upload"
:on-change="fileOnChange"
:on-remove="fileOnRemove"
:multiple="true"
action="#"
name="files"
:file-list="fileList"
:auto-upload="false"
:on-preview="handlePreview"
list-type="picture-card"
>
<i slot="default" class="el-icon-plus"></i>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过500kb
</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="" />
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [],
dialogImageUrl: "",
dialogVisible: false
};
},
methods: {
submitUpload() {
// new 一个 FormData()
let formData = new FormData();
this.fileList.forEach(e => {
// 遍历上传的图片数组,把每个图片的文件流 添加进 formData中
formData.append("files", e.raw);
});
// 这里可以添加需要上传的其他参数字段;
// 注意:formData.append的值只能是字符串或者blob(File)格式, 复杂的数组或者对象的数据无法添加
formData.append("stepId", this.stepId);
formData.append("describe", this.describe);
formData.append("time", this.time);
// 上传
this.$http({
url: "后端给的接口",
method: "post",
// 这里直接把 formData 传给 data
data: formData,
upload: true,
// 设置 请求头 ,以表单的形式上传
headers: { "Content-Type": "multipart/form-data;charset=utf-8" }
}).then(({ data }) => {
// console.log(data);
if (data && data.code === 0) {
} else {
this.$message.error(data.msg);
}
});
},
fileOnRemove(file, fileList) {
this.fileList = fileList;
},
fileOnChange(file, fileList) {
this.fileList = fileList;
},
handlePreview(file) {
// console.log(file, "点击放大");
this.dialogImageUrl = file.url;
this.dialogVisible = true;
}
}
};
</script>
<style lang="scss">
.flex {
display: flex;
}
.flex-1 {
flex: 1;
}
.upload-img {
flex-direction: column;
justify-content: center;
align-items: center;
.el-upload__tip {
text-align: center;
}
}
</style>
在上传文件流时,要注意在接口的封装拦截那里有没有对上传数据进行什么转换或更改(被坑了)