*(00)*

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  613 随笔 :: 0 文章 :: 45 评论 :: 159万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

我们不需要根据服务器返回的情况去随机设置responseType

一、我们要明白,我们在请求下载文件的api时候,可能给我们的返回值有两种情况:

  1. 直接给我们了我们想要的文件流
  2. 还有可能得到了JSON返回数据,让我们展现提示出信息或者被叫为错误信息

二、理解responseType
axios中这样描述的:responseType`表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
不过我经常用blob,其实用什么都无所谓,主要看在拿到返回值的时候如何处理。

三、处理返回值的不同情况

复制代码
const API = axios.create({
  baseURL: API_HOST
})
API({
      method: 'get',
      url: file.url,
      responseType: 'blob'
    }).then(response => {
    
        const type = response.type || null
        
        //relType你所下载的文件类型,这里是xlsx
        const relType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        if (type.includes(relType)) {
          /**做文件下载 */
          
          return
        }

        if (type.includes('application/json')) {
            let reader = new FileReader()
            reader.onload = e => {
                if (e.target.readyState === 2) {
                  let res = {}
                  res = JSON.parse(e.target.result)
                  console.info('back:: ', res)
                }
           }
           reader.readAsText(response)
        }
      
    })
复制代码

根据response.type返回内容的MIME TYPE 来判断是要下载文件,还是要去做一些JSON数据提示什么的操作。如果是JSON类型那就把Blob通过readAsText转为JSON格式。这种方式通过测试IE10和IE10以上版本。

可以尝试在arrayBuffer的情况下使用arrayBuffer to Json来进行信息提示。

 

posted on   *(00)*  阅读(820)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示