下载文件
以前做下载功能的时候都是用的a标签直接href等于下载地址就可以了,直接连接到了文件地址,有时候可能都不会走到后台
今天在项目中也有一个下载功能,但是要确保用户在登录的情况下下载,也就是说要走后台的用户验证,
public ResponseEntity<byte[]> getPath(String name) {
File file = new File(path+name);
byte[] fileByte = new byte[(int) file.length()];
try {
FileInputStream fis = new FileInputStream(file);
fis.read(fileByte);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try {
httpHeaders.setContentDispositionFormData("attachment",new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(fileByte,httpHeaders, HttpStatus.OK);
}
这样在前端直接用a调用接口就可以了
<a :href="path+'/techDownload/download?name=业务系统Demo (Web Java).rar'>