admin管理员组文章数量:1535147
前端代码
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 {
//filePath示例:sftp://abc:abc@127.0.0.1/defg/hijk(sftp://【用户名】:【密码】@【IP地址/..】)
//ftp服务器文件路径通过VFS自动解析
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;
//返回字节流IOUtils.toByteArray(in)
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;
}
版权声明:本文标题:java开发:读取ftp服务器文件通过浏览器下载 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1726897009a1089172.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论