前端代码
window.location.href=this.contextPath+"【路径】?filePath="+【文件路径】+"&fileName="+【下载后的文件名】
java后台代码
private static FileSystemManager fsManager = null;
static {
try {
fsManager = VFS.getManager();
} catch (FileSystemException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/【路径】", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<byte[]> getFile(@RequestParam(required = true) String filePath,
@RequestParam(required = true) String fileName) throws IOException {
ResponseEntity<byte[]> entity = null;
if (StringUtils.isEmpty(filePath)) {
throw new IOException("File'" + filePath + "'is empty");
} else {
FileObject fileObj = null;
InputStream in = null;
File file = new File(fileName);
try {
fileObj = fsManager.resolveFile(filePath);
if (fileObj.exists()) {
if (FileType.FOLDER.equals(fileObj.getType())) {
throw new IOException("File'" + filePath + "'exists but is directory");
} else {
in = fileObj.getContent().getInputStream();
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", file.getName());
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
HttpStatus status = HttpStatus.OK;
entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, status);
}
} else {
throw new IOException("File'" + filePath + "'is not exists");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(in);
if (fileObj != null) {
try {
fileObj.close();
} catch (FileSystemException e) {
e.printStackTrace();
}
}
}
}
return entity;
}