vue element ui 图片和文件上传 图片base64转化 请求接口 请求前需要改请求头
在页面上
http-request: 覆盖默认的上传行为,可以自定义上传的实现
<el-upload
class="avatar-uploader"
action=""
:show-file-list="false"
:on-success="handleAvatarSuccess"
:http-request="requests">
<img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
请求前需要改请求头
config.headers['Content-Type'] = ' multipart/form-data'
上传图片请求接口 请求前需要改请求头
config.headers['Content-Type'] = ' multipart/form-data' //必须要加的
config.headers['Authorization'] = store.userStore.token
方法中:
// 上传图片
handleAvatarSuccess(res, file) {
this.ruleForm.imageUrl = res.msg;
this.$forceUpdate()
},
新写请求:
requests(file){
let that = this
let isJPG = ['image/jpeg', 'image/png', 'image/jpg'];
const isImg =isJPG.includes(file.file.type)
const isLt2M = file.file.size / 1024 / 1024 < 1;
if (!isImg) {
this.$message.error('请上传正确的LOGO格式!');
return false
}
if (!isLt2M) {
this.$message.error('上传LOGO大小不能超过 1MB!');
return false
}
let fd = new FormData();
fd.append('file', file.file);//传文件
let loading = this.$loading()
//下面是接口请求
tenantUpload(fd).then(res => {
that.ruleForm.imageUrl = res.data.msg;
that.$forceUpdate()
}, this.err).finally(() => loading.close())
},
//第二种上传
<input ref="filElem" type="file" class="upload-file" accept=".xlsx, .xls,.csv" style="display: none" @change="getFile"/>
<el-button type="primary" @click.native="importFile">导入</el-button>
方法:
// 导入
importFile() {
this.$refs.filElem.dispatchEvent(new MouseEvent("click"));
},
getFile() {
let that = this;
let param = this.$refs.filElem.files[0];
let formData = new FormData();
formData.append("medical_import", param);
// this.$axios({
// url: "http://195.195.8.157/v3/api/medical/service/excel/import", // 请求的 url 地址
// method: "post", // 请求方式
// data: formData, // 传递的参数
// })
// .then((res) => {
// if (res.data.code == 200) {
// that.$message.success(res.data.message);
// } else {
// that.$message.error(res.data.message);
// }
// })
// .catch((err) => {
// console.log(err);
// });
this.$familyNewAddUrl
.post("/medical/service/excel/import", formData, {
"Content-Type": "application/x-www-form-urlencoded",
})
.then((res) => {
if (res.data.code == 200) {
that.$message.success(res.data.message);
} else {
that.$message.error(res.data.message);
}
});
},
//图片转base64
urlToBase64(url) {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = function () {
const canvas = document.createElement("canvas");
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
// 将图片插入画布并开始绘制
canvas.getContext("2d").drawImage(image, 0, 0);
// result
const result = canvas.toDataURL("image/png");
resolve(result);
};
// CORS 策略,会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
image.setAttribute("crossOrigin", "Anonymous");
image.src = url;
// 图片加载失败的错误处理
image.onerror = () => {
reject(new Error("转换失败"));
};
});
},
第四种 vue3 element-plus
<el-upload
class="avatar-uploader"
style="position: relative"
:action="action"
:headers="{ 'Platform-Name': 'avatar' }"
list-type="picture"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeUpload"
>
<img class="camera" src="@/assets/hmm/11.png" />
<el-avatar v-if="state.parentData.userInfo.avatar" :src="state.parentData.userInfo.avatar"></el-avatar>
<el-avatar v-else>{{ userFirstName }}</el-avatar>
</el-upload>
// 上传之前判断格式
// 上传之前判断格式
const beforeUpload = file => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
if (!isJpgOrPng) {
ElMessage.error('只支持JPG、PNG格式!')
return Promise.reject()
}
const isLt2M = file.size / 1024 / 1024 > 2
if (isLt2M) {
ElMessage.error('图片大小不能超过2MB!')
return Promise.reject()
}
}
//上传成功const handleAvatarSuccess: UploadProps['onSuccess'] = (res, file) => {
if (res.code !== 0) {
ElMessage.error('上传失败:' + res.message)
return false
}
console.log(res.data.url)
if (res.data.url) {
state.parentData.userInfo.avatar = res.data.url
if (!state.parentData.userInfo.postIdList) {
state.parentData.userInfo.postIdList = []
}
if (!state.parentData.userInfo.roleIdList) {
state.parentData.userInfo.roleIdList = []
}
// console.log(state.parentData.userInfo)
useUserSubmitApi(state.parentData.userInfo).then(res => {
roleListFun(state.parentData.userInfo.orgId)
})
}
// dataForm.name = res.data.name
// dataForm.type = res.data.suffix
// dataForm.fileUrl = res.data.url
// dataForm.size = res.data.size
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具