axios在Post请求中同时传递文件和对象

有时候前端往后端传值,需要同时传递文件和其他数据,如果是小数据的参数可以直接通过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) {}
    

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值