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;
    }

本文标签: 浏览器服务器文件JavaFTP