默认展示
点击上传之后的样子 (在重新选择图片的时候直接点击图片即可)
<el-form label-width="120px" :model="formData" ref="formData">
//show-file-list 是否显示已上传文件列表
//http-request 覆盖默认的上传行为,可以自定义上传的实现
//handleAvatarSuccess 文件上传成功时的钩子
//beforeAvatarUpload 上传文件之前的钩子
<el-form-item :label="label" prop="url">
<el-upload
class="avatar-uploader"
action="1"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:http-request="upload"
>
<img v-if="formData.url" :src="formData.url" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
</el-form>
data:
formData: {
url: "", //图片地址
},
上传封装的js uploadfile.js
import axios from 'axios'
import { getToken } from '@/utils/auth'//获取token的
const baseURL = process.env.VUE_APP_BASE_API
export function UploadFile(url, FormData) {
return axios.post(baseURL + url, FormData,
{
headers: {
'Content-Type': 'multipart/form-data',
'api-version': '1.0',
'token': getToken()
}
}
)
}
methods:
import { UploadFile } from "@/utils/uploadfile.js";
//上传的代码
upload(file) {
var formdata = new FormData();
formdata.append("file", file.file);
UploadFile("/file/upload", formdata).then((res) => {
console.log(res.data.data, "==res===");
this.formData.url = res.data.data;
this.$message.success(res.data.message);
});
},
//文件上传成功时的钩子
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
//上传文件之前的钩子
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}