我用的是点击a标签,然后文件下载的方法。
前端代码:
<a class="layui-btn" onclick="DownLoad()">模板下载</a>
<script type="text/javascript">
function DownLoad(){
window.open(url="http://localhost:8080/medicalSystem/login/download");
}
</script>
显示效果:
后端的代码(用的是SpringMVC,所在写在controller里面:
@RequestMapping(value="download")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
// File file = new File("C:\\Users\\dell\\Desktop\\chemicalDate.xlsx");
String path=this.getClass().getResource("/chemicalDate.xlsx").getPath();
File file=new File(path);
byte[] body = null;
InputStream is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<>(body, headers, statusCode);
return entity;
}
我存放的文件位置在src下面,所以要用代码:
this.getClass().getResource("/里面加src为起点的后面的文件路径").getPath();
我的文件路径为:
this.getClass().getResource("/chemicalDate.xlsx").getPath()
对应的文件位置为:
此外,还有一点是,如果文件是在本地磁盘下面,则很简单的本地磁盘下的绝对路径就可以了,比如:
File file = new File("C:\\Users\\dell\\Desktop\\chemicalDate.xlsx");