前端下载文件流,axios设置responseType: arraybuffer/blob无效

 

项目中调用后端下载文件接口,设置responseType: 'arraybuffer',实际拿到的数据data是字符串

axios({
        method: 'post',
        url: '/api/v1/records/recording-file/play',
        // 如果有需要发送的数据,可以放在这里
        data: { uuid: '06e7075d-4ce0-476f-88cb-87fb0a1b4844' },
        responseType: 'arraybuffer', // 设置期望的响应类型为 arraybuffer
      }).then(response => {
        console.log(typeof response.data); // string
      })

转成blob下载文件下来打开破坏,postman可以,项目总不可以,下载的文件MD5不一样,大小不一样!

折腾查找原因查了很久,最后发现新写的项目里调用接口axios是正常的arraybuffer,老项目里string是请求的responseType被项目中引入的mockjs置空了。

mockjs的源码里搞了这一出,大大的无语查了好久。 

关掉mockjs,就正常接口responseType类型的数据了,文件MD5也对应上了,文件也能正常打开了

从错误信息来看,`responseType` 参数的类型定义存在问题。具体来说,`axios` 的 `responseType` 属性接受的是一个有限制的枚举值(如 `'arraybuffer'`, `'blob'`, `'document'`, `'json'`, `'text'`, `'stream'`),而你将其定义为了普通的字符串类型 `string`。因此 TypeScript 报错提示:`Type 'string' is not assignable to type 'ResponseType | undefined'`。 --- ### 解决方案:修正 `responseType` 类型 你需要明确地指定 `responseType` 只能接收合法的值,而不是任意字符串。可以通过以下方式解决: #### 改进后的代码: ```typescript import axios from 'axios'; export async function axiosGet( url: string, params: any = null, ContentType: string = 'application/json', token: string, responseType?: AxiosResponseTypes // 定义为可选参数 ): Promise<any> { return axios("http://127.0.0.1:8080" + url, { method: 'get', headers: { 'Content-Type': ContentType, 'token': token }, responseType: responseType || 'json', // 默认值为 'json' params: params }); } // 定义合法的 responseType 枚举类型 type AxiosResponseTypes = | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'; ``` --- ### 关键点解析: 1. **`responseType` 的类型限定** - `axios` 内部对接收的 `responseType` 进行了严格的校验,仅允许特定的值。 - 因此我们需要使用枚举类型的联合 (`|`) 来限定其取值范围,例如上面的 `AxiosResponseTypes`。 2. **默认值设置** - 如果用户未传入 `responseType`,我们可以为其提供默认值 `'json'`,保证函数调用时不会报错。 3. **参数可选项** - 添加了 `?` 符号标记 `responseType` 为可选参数,避免使用者必须每次传递该值。 4. **返回值泛型化** - 函数最终返回的是 `Promise<any>` 类型,如果你需要更精确的结果类型,可以根据实际需求替换掉 `any`。 --- ### 示例调用: ```typescript try { const response = await axiosGet('/api/data', { id: 1 }, 'application/json', 'your_token_here', 'blob'); console.log(response); } catch (error) { console.error(error); } ``` --- ### 错误原因总结: 原始代码中将 `r
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yusirxiaer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值