在开发前端vue项目是遇到一个批量导入(导入表格csv)功能,前端框架统一使用用axios发的请求,所以就不加思索得就用的axios请求。
由于后端接收上传的scv文件,需要请求头为“multiple/form-data”,所以单独用axios.create,单独做了给上传文件的配置:
import qs from 'qs'
import axios from "axios"
const Axios = axios.create({
baseURL: 'baseURL', // 远程接口ip及端口
method: 'post',//请求方法
withCredentials:true ,
headers: {'Content-Type': 'multiple/form-data'},//请求头 'multiple/form-data'
transformRequest: [function (data) {
const d = qs.stringify(data)
return d;
}]
})
// 页面
<el-button size="small" @click="$refs.selectFile.click()">批量导入</el-button>
<input ref="selectFile" type="file" accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="display:none" @change="selectFile" />
// methords
selectFile(e) {
for (let file of e.target.files) {
this.uploadFile(file)
}
},
uploadFile(file) {
console.log(file)
var fd = new FormData();
fd.append("file", file);
Axios.post('url',fd)
},
本以为平安无事,但是后台一直报跨域,非说前端请求头有问题,最后试了很多请求头,都一样,最后还是后台来解决跨域问题。最后跨域问题是解决了但是后台又没有接收到前台传的参数。
最后发现是var fd = new FormData();这一步得到的是空值:
也没查到是什么问题,最后决定不用axios了,修改后为:
uploadFile(file) {
var fd = new FormData();
fd.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open('POST', this.upload, true);
xhr.send(fd);
xhr.onreadystatechange = (val) => {
// console.log(val, "onreadystatechange")
this.$refs.selectFile.setAttribute("type", "text")
if (val.target.readyState == 4 && val.target.status == 200) {
let rsp = JSON.parse(val.target.response);
// console.log(rsp, "判断条件")
var b = rsp.status;
this.$refs.selectFile.setAttribute("type", "file")
if (b) {
this.$message({
message: '导入成功',
type: 'success',
duration: 2000
})
// 清空页面数据重新到接口渲染页面
} else {
this.$message({
message: '导入失败:' + rsp.data[0].bcwz + rsp.data[0].cwyy, // 失败详情
type: 'error',
duration: 4000
})
}
}else{
// this.$refs.selectFile.setAttribute("type", "file")
}
};
},
这里做个纪录后期再查问题,再封装成组件。