axios接收zip文件文件
问题代码
async previewLoadRequest(end){const response = await axios.get('/api2/pdfToImage', {params: { path: this.file.path ,startPage: this.endPage, // 开始页码endPage: end , // 结束页码},});if(response.status != 200){return false}console.log('response',response)console.log('response.data',response.data)// 2. 解压ZIP文件const zip = new JSZip();// const zipData = await zip.loadAsync(response.data);const blob = new Blob([response.data], {type: 'application/zip'});const zipData = await zip.loadAsync(blob);for (const [name, file] of Object.entries(zipData.files)) {console.log('name',name)if (!file.dir) { // 跳过目录const blob = await file.async('blob');const url = URL.createObjectURL(blob);this.urls.push(url);}}return true
},
抛出错误
fileCard.vue:154 处理失败: Error: Corrupted zip:
missing 40318 bytes. at h.readEndOfCentral
(jszip.min.js:13:1) at h.load (jszip.min.js:13:1)
at eval (jszip.min.js:13:1)
at async Proxy.previewHandler (fileCard.vue:138:1)
首要排查的是是否没加上responseType: 'blob'
或 responseType: 'arraybuffer'
导致的二进制数据接收异常。
加上后解决
async previewLoadRequest(end){const response = await axios.get('/api2/pdfToImage', {params: { path: this.file.path ,startPage: this.endPage, // 开始页码endPage: end , // 结束页码},responseType: 'blob' // 设置响应类型为 Blob非常重要不能省略});if(response.status != 200){return false}console.log('response',response)console.log('response.data',response.data)// 2. 解压ZIP文件const zip = new JSZip();// const zipData = await zip.loadAsync(response.data);const blob = new Blob([response.data], {type: 'application/zip'});const zipData = await zip.loadAsync(blob);for (const [name, file] of Object.entries(zipData.files)) {console.log('name',name)if (!file.dir) { // 跳过目录const blob = await file.async('blob');const url = URL.createObjectURL(blob);this.urls.push(url);}}return true
},