Vue封装文件ajax请求,整合el-upload
作者:互联网
前端
<el-upload :multiple="false" //不可上传多个文件 action="" //必要参数,使用ref方式提交时的url :on-change="setAvatarFile" //文件列表变化时的钩子,用来获取当前的文件 :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" //禁用自动上传 > <el-button slot="trigger" size="small" type="primary" >选取头像文件</el-button > //请求函数 <el-button @click="submitUploadAvatar">修改头像</elbutton>
组件在文件请求过程中只承担了帮助请求体获取文件二进制流的任务
setAvatarFile(file,fileList) { this.avatarFile = file; },
submitUploadAvatar() { var params = { test1: "test1", }; var data=new FormData() data.append("avatar",this.avatarFile.raw) data.append("test2","-----------------------") //值为二进制的时候这种没法带参数 // var data2={ // avatar:this.avatarFile.raw // } allapi .updateAvatar(data, params) .then((res) => { var data = res.data; if (data.code == 200) { this.$message({ type: "info", message: data.data, }); this.fileList=[] this.getPersonalInfo(); } else { this.$message({ type: "error", message: data.data, }); } }) .catch((err) => { console.log("createNewStaff失败"); }); },
import axios from 'axios' //总的后台url接口配置 export const baseURL="http://localhost:8081"; // 创建axios实例 const service = axios.create({ baseURL:baseURL, timeout: 60000 // 请求超时时间 }) // request拦截器 service.interceptors.request.use( config => { // console.log(i18n.locale) // debugger; // if(i18n.locale){ // config.data.lang = i18n.locale.toLocaleUpperCase() // } // console.log(config.data) if (localStorage.getItem("Token_JWT")) { // 判断是否存在token,如果存在的话,则每个http header都加上token config.headers.Authorization = `${localStorage.getItem("Token_JWT")}`; config.headers.StaffJobNum=`${localStorage.getItem("StaffJobNum")}`; } config.headers['Content-Type'] = 'multipart/form-data; boundary=----WebKitFormBoundaryyTHrmBEZGIQHBeAc' return config }, error => { // Do something with request error console.log(error) // for debug Promise.reject(error) } ) // response 拦截器 service.interceptors.response.use( response => response, error => { return Promise.reject(error) } ) export default service
后端
@RequestParam("avatar") MultipartFile avatar,@RequestParam("test2") String test2,@RequestParam("test2") String test2
标签:el,Vue,console,data,upload,test2,error,config,axios 来源: https://www.cnblogs.com/JNU-Iot-Longxin/p/16550690.html