前端代码片段 - zipDownload.js
import axios from 'axios'
import baseURL from './baseUrl'
const mimeMap = {
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
zip: 'application/zip'
}
export function downLoadZip(str, filename) {
var url = baseURL + str
axios({
method: 'get',
url: url,
responseType: 'blob',
headers:{ 'Content-Type': 'application/json; application/octet-stream'}
}).then(res => {
resolveBlob(res, mimeMap.zip)
})
}
/**
* 解析blob响应内容并下载
* @param {*} res blob响应内容
* @param {String} mimeType MIME类型
*/
export function resolveBlob(res, mimeType) {
console.log(res)
const blob = new Blob([res.data]);
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob);
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
var contentDisposition = decodeURI(res.headers['content-disposition'])
var result = patt.exec(contentDisposition)
var fileName = result[1]
fileName = fileName.replace(/\"/g, '')
//后台再header中传文件名
const name = fileName;
downloadElement.href = href;
downloadElement.download = name;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
}
前端使用方式:
import { downLoadZip } from '@/axios/download.js'
...
downLoadZip(apis.GENERTOR_ROAD_MAP_CODE+'/'+this.roadMapItem.mapId, "SoFly-Crane");
...
Java后端代码:Controller
//实现逻辑部分 - genTableService.generatorCode(){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
StringWriter sw = new StringWriter();
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, craneProjectRoadMap)));
IOUtils.write(sw.toString(), zip, Constants.UTF8);
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();
return outputStream.toByteArray();
}
//请求相应部分
@GetMapping("/genCode/{mapId}")
public void genCode(HttpServletResponse response, @PathVariable("mapId") Long mapId)
{
try {
byte[] data = genTableService.generatorCode(mapId);
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=\"crane.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
} catch (Exception e) {
writeTextJson(JsonUtils.getSimpleMapJson(null));
e.printStackTrace();
}
}
如果下载后打开压缩包,出现文件损坏问题,可以通过前端debug到resolveBlob方法位置,查看responseType是否为blob。
这种情况有可能是在前端项目中使用了Mock导致的,将Mock的引用去掉即可。
// if (process.env.NODE_ENV === 'development') require('@/mock')