第一种 使用它的action方法
<el-upload
class="upload-demo"
:headers="token"
action="http://120.53.31.103:84/api/public/img"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="sizeForm.fileList"
list-type="picture"
:on-success="successImg"
>
<!-- 上传图片 headers提交token action提交地址 on-success成功回调 三个比较重要 -->
//这是标签中的token的数据源 token我们通过headers来进行传递
data() {
return {
token: {
Authorization: "Bearer" + localStorage.getItem("adminToken") || ""
}
};
},
//上传成功的回调函数
successImg(res, file) {
console.log(res, file);
if (res.code === 200) {
//res.data.path 是服务器返回的当前图片的网络地址
this.sizeForm.avatar = res.data.path;
this.sizeForm.fileList.push(file);
console.log(res.data.path);
}
}
第二种 不使用action
使用before-upload方法,这是文件上传前的钩子,它的参数就是当前操作的这个文件(就是上传的文件/图片)
执行的函数为
<el-upload
class="upload-demo"
action="abc"
:limit="1"
:show-file-list="false"
:before-upload="onprog"
>
<el-button size="small" type="primary">上传文件</el-button>
</el-upload>
onprog(file) {
//创建formdata实例
var formData = new window.FormData();
//将获取的文件通过append方法加入实例中
formData.append("file", file);
console.log(formData);
//将formdata实例通过接口传递给服务器
uploading_image(formData).then(res => {
var type, message;
console.log(res.data);
if (res.data.code === 200) {
//文件内容不符合服务器需求 data的值是一个err数组 若符合data的值是一个数字
if (res.data.data.err) {
// type = "success";
this.err = res.data.data.err;
this.dialogVisible = true;
} else {
type = "success";
message = `共${res.data.data}条,上传成功`;
this.$message({
type,
message
});
}
} else {
this.$message({
type: "error",
message: res.data.msg
});
}
});
}
uploading_image是封装的请求 使用前要替换