VUE下载文件,正确则下载,错误则解析提示错误信息,比如文件不存在(需要后端配合,后端springboot写入到response)
VUE前端代码
axios({
method: 'get',
url: window.location.origin + '/xxx/download?fileName=' + name+'&id='+id,
responseType: 'arraybuffer',
changeOrigin: true,
})
.then(res => {
let enc = new TextDecoder();
let uint8_msg = new Uint8Array(res.data);
let response = enc.decode(uint8_msg);
if (response.includes('msg')) {
Message.error(JSON.parse(response).msg)
return true
}else{
Message({
message: '下载中...',
type: "warning",
duration: 3 * 1000
});
let filename = name + '-service.zip'
let temp = res.headers["content-disposition"]
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
let matches = filenameRegex.exec(temp);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
let blob = new Blob([res.data], {type: res.headers['content-type']});
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(downloadUrl);
Message({
message: '下载完成',
type: "success",
duration: 3 * 1000
});
return true
}
})
.catch(function (error) {
Message({
message: '下载异常!',
type: "error",
duration: 3 * 1000
});
console.log('catch error',error)
})
springboot代码
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment;filename=").append(percentEncodedFileName).append(";").append(
"filename*=").append("utf-8''").append(percentEncodedFileName);
response.setHeader("Content-disposition", contentDispositionValue.toString());
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
try (FileInputStream fis = new FileInputStream(file);) {
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (IOException e) {
throw e;
}
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
Map<String, Object> m = new HashMap<>();
m.put("msg", e.getMessage());
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(JSONObject.toJSONString(m));
} catch (IOException ex) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}