有时候前端往后端传值,需要同时传递文件和其他数据,如果是小数据的参数可以直接通过URL路径拼接 uploadExcel?menuId=${menuId},然后在后端接收参数
public uploadExcel(menuId: string, file: any): Promise<any> {
let headerParams = { 'Authorization': undefined };
headerParams.Authorization = localStorage.getItem('Authorization');
return axios({
method: 'POST',
url: `/app/versionManager/uploadExcel?menuId=${menuId}`,
responseType: 'blob',
data: file,
headers: headerParams,
});
}
如果出现需要传递不确定数据量的一些对象map、list等,可以通过以下方式传递数据
数据转为JSON传递:fdata.append('dictMap', JSON.stringify(this.dictMap))
private uploadFile(file, fileList) {
const fdata = new FormData()
fdata.append('dictMap', JSON.stringify(this.dictMap))
fdata.append('file', file.file)
...
this.service.uploadExcel(id, fdata).then(res => {})
}
public uploadExcel(menuId: string, file: any): Promise<any> {
let headerParams = { 'Authorization': undefined };
headerParams.Authorization = localStorage.getItem('Authorization');
return axios({
method: 'POST',
url: `/app/versionManager/uploadExcel?menuId=${menuId}`,
responseType: 'blob',
data: file,
headers: headerParams,
});
}
responseType: 'blob':作用是指定响应的数据类型为二进制数据流(Blob对象),以便在JavaScript中进行处理和操作。
注释掉改行后,通过res.data获取返回的数据
在后端接收数据
@ApiOperation("导入数据")
@RequestMapping(value = "uploadExcel", produces = "application/json")
public void uploadExcel(@RequestParam("dictMap") String dictMap, @RequestParam("file") MultipartFile file, @RequestParam("menuId") String menuId, HttpServletResponse response) {}