文件下载 乱码 文件损坏 打开undefind等几个坑点 |
您所在的位置:网站首页 › 前端生成图片下载格式不对怎么回事 › 文件下载 乱码 文件损坏 打开undefind等几个坑点 |
前端请求二进制文件流,返回的是乱码,如下图: 这个时候点击导出或者下载,文件就下下来了,重点在于打开可能会出现文件损坏,文件打开undefind. 两个点: 前后端分别检查,返回的形式是否为blob形式.![]() 前端用原生axios写,否则responseType会设置无效. axios的Authorization需要配置的别忘记: axios.defaults.headers.common["Authorization"] =token; axios({ method: 'POST', url: `${link}/case/message/excel/export`, data: selectedRowKeys, responseType: 'blob' }).then(res => { //可以在此处加格式判断,以下代码以excel文件下载为例. let blob = new Blob([res.data], {type: "application/vnd.ms-excel"}); // console.log(blob) FileSaver.saveAs(blob, "案件列表.xls"); message.success("下载成功!", 2); }).catch(err => { console.log(err) }) 注意: application/vnd.ms-excel 是对应xls application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 是xlsx xlsx可能会有excel版本兼容问题,word同理. 不知道下下来是个什么格式,可以自己在加个判断 const content = res.data let temp = res.headers["content-disposition"] let isExcel = temp.indexOf(".xlsx") > 0 || temp.indexOf(".xls") > 0 let isWord = temp.indexOf(".docx") > 0 || temp.indexOf(".doc") > 0 let file = {} if(isExcel){ file.type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' file.name = temp.indexOf(".xlsx") > 0 ? 'xlsx' : 'xls' }else if(isWord){ file.name = temp.indexOf(".docx") > 0 ? 'docx' : 'doc' file.type = 'application/msword;charset=UTF-8' } // const blob = new Blob([content], {type: res.data.type}) const blob = new Blob([content], {type: file.type}) const fileName = `${row.title}.${file.name}` 顺便看下前端在axios的属性设置里有没有设置 withCredentials:true, 这个要跟后端对应,因为后端没有开启就会出现请求问题. Access-Control-Allow-Credentials:true, 开启了没有,后端检查下. 后端可能会出现拦截,从而不按请求返回blob对象.一般是框架的问题了. 前端的index.js的入口文件,有没有引入mock生成的数据文件,文件里引用了mockjs,mock会对返回的数据做处理,导致文件损坏.都确认没问题后,下载打开文件基本没啥问题了,至少目前还没遇上其他坑,心累… |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |