效果:
举例下载"E:\test\jn_ceshi1202.txt"
则前端realPath=“E:\test\jn_ceshi1202.txt”
前端:
downloadFile(realPath) {
downloadFile(realPath).then(res => {
const link = document.createElement('a')
link.href = window.URL.createObjectURL(new Blob([res]))
link.target = '_blank'
// 文件名和格式
link.download = 'jn_ceshi1202.txt'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
this.msgSuccess('下载完成')
})
}
后端:
@PostMapping("/downloadFile/{realPath}")
public AjaxResult downloadFile(@PathVariable("realPath") String realPath, HttpServletResponse response)
{
String realPath = pushBakInfo.getBakPath();
InputStream in = null;
OutputStream out = null;
try {
File file = new File(realPath);
in = new FileInputStream(file);
int len;
byte[] buffer = new byte[1024];
out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
// 文件传输完成
return AjaxResult.success();
} catch (Exception e) {
e.printStackTrace();
// 文件传输失败
return AjaxResult.error("下载失败:"+e.getMessage());
}finally {
try {
if (null != out) {
out.close();
}
if(null != in){
in.close();
}
} catch (IOException var3) {
var3.printStackTrace();
}
}
}