VUE 下载文件流 文件无法打开,缺失数据
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
·
项目场景:
项目场景:VUE工程,做了一个代码自动生成可以导出zip的功能。
问题描述
导出的zip文件打开提示“不可预料的压缩文件末端”,文件打不开。
export function downLoadZip(str, filename) {
var url = baseUrl + str
axios({
method: 'get',
url: url,
responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() }
}).then(res => {
resolveBlob(res, mimeMap.zip)
})
}
原因分析:
分析是返回的数据流有丢失,所以在上面的代码段将返回的res的结果给打印出来。
- 发现返回的data是一串乱码,并不是blob格式的文件流。

- 通过这个情况,在网上搜了半天,才发现是Mockjs污染了responseType,默认会将responseType变为’’
- 那么第一种解决办法已经有了,就是修改Mockjs,文件路径是node_modules>mockjs>dist>mock.js
// 原生 XHR
if (!this.match) {
this.custom.xhr.responseType = this.responseType //新加的解决该问题的代码
this.custom.xhr.send(data)
return
}
- 那么这样改后,重新编译,测试,发现问题解决,返回值如下图。

- 但是这样只适合个人开发,实际上协同开发,或者用Jenkins自动部署时,会从npm下载Mockjs的源码,还是会有问题,那么怎么在不改Mockjs源码的情况下,解决该问题呢?
解决方案:
那么唯一的解决办法就是重写mockjs相关的部分,具体代码参考下面的
// 修复 mockjs 相关 bug
Mock.XHR.prototype.send = (() => {
const _send = Mock.XHR.prototype.send
return function() {
if (!this.match) {
this.custom.xhr.responseType = this.responseType || ''
this.custom.xhr.timeout = this.timeout || 0
this.custom.xhr.withCredentials = this.withCredentials || false
this.custom.xhr.onabort = this.onabort || null
this.custom.xhr.onerror = this.onerror || null
this.custom.xhr.onload = this.onload || null
this.custom.xhr.onloadend = this.onloadend || null
this.custom.xhr.onloadstart = this.onloadstart || null
this.custom.xhr.onprogress = this.onprogress || null
this.custom.xhr.onreadystatechange = this.onreadystatechange || null
this.custom.xhr.ontimeout = this.ontimeout || null
}
return _send.apply(this, arguments)
}
})()
具体代码查看 mock文件完整代码
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:3 个月前 )
9e887079
[skip ci] 1 年前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)