1.常规的是使用了"mock" ,但是本vue项目没有使用到"mock"
后端代码
@RequestMapping("/code/generateDownLoad")
public void generateDownLoad(@RequestBody ParamInfo paramInfo, HttpServletResponse response) throws Exception {
ClassInfo classInfo = null;
String dataType = MapUtil.getString(paramInfo.getOptions(),"dataType")
paramInfo.getOptions().put("classInfo", classInfo);
paramInfo.getOptions().put("tableName", classInfo == null ? System.currentTimeMillis() : classInfo.getTableName());
byte[] data = generatorService.downLoad(paramInfo.getOptions());
response.setHeader("Content-Disposition", "attachment; filename=\"renren.zip\"");
response.addHeader("Content-Length", "" + data.length);
// 这里要声明返回的是二进制
response.setContentType("application/octet-stream; charset=UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
try{
outputStream.write(data);
}finally {
outputStream.close();
}
}
错误的前端代码
generateDownLoad : function(){
vm.formData.tableSql=$.inputArea.getValue();
let config = {
headers: {
'Content-Type': 'application/json; application/octet-stream'
}
};
axios({
method: 'post',
url: "code/generateDownLoad",
data: vm.formData,
responseType: 'arraybuffer',
headers: {'Content-Type':'application/json; application/octet-stream'}
}).then(function (data) {
debugger
let blob = new Blob([data.data],{type:'application/zip'});
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', 'file.zip'); //any other extension
document.body.appendChild(link);
link.click();
document.body.removeChild(link); //下载完成移除元素
window.URL.revokeObjectURL(downloadUrl); //释放blob对象
})
.catch(function (error) {
console.log(error);
});
},
下载下来的zip 包解压失败 未预料的解压末端
几点原因
1.axios.post() 这种写法,是不支持写入responseType的,即使写了,底层也没调用
2.使用axios(method:'post',config) 这种依然不可以,报不支持 arraybuffer,是因为axios 的版本低。找一个最新的版本
3.responseType 未设置
定位方式:debugger 可以看到响应里面的responsType="" 应该是responsType="arraybuffer"
最后升级axios的版本,并且修改axios post 的请求方式成功解决
解决后的前端代码
generateDownLoad : function(){
vm.formData.tableSql=$.inputArea.getValue();
// 注意这里的写法已经改变
axios({
method: 'post',
url: "code/generateDownLoad",
data: vm.formData,
responseType: 'arraybuffer',
headers: {'Content-Type':'application/json; application/octet-stream'}
}).then(function (data) {
debugger
let blob = new Blob([data.data],{type:'application/zip'});
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', 'file.zip'); //any other extension
document.body.appendChild(link);
link.click();
document.body.removeChild(link); //下载完成移除元素
window.URL.revokeObjectURL(downloadUrl); //释放blob对象
})
.catch(function (error) {
console.log(error);
});
}