vfs2 - sftp文件在下载过程中损坏

时间:2016-09-13 23:38:48

标签: download sftp apache-commons-vfs

我正在使用vfs2通过sftp下载文件。

.txt.xml文件正在正确下载,但.pdf文件正在下载已损坏。

以下是我的代码:

有人看到我做错了吗?

import org.apache.commons.vfs2.*;    
public void downloadFile(HttpServletResponse response, HttpServletRequest request, String localFilePath, String fileName) throws Exception
{
            OutputStream outStream = null;
            StandardFileSystemManager manager = new StandardFileSystemManager();
            boolean success = false;
            String remoteFilePath = localFilePath.replaceAll("^[a-zA-Z]:", "");

            try{
            manager.init();
            FileObject remoteFile = manager.resolveFile(createConnectionString(remoteFilePath), createDefaultOptions());
            InputStream istream = remoteFile.getContent().getInputStream();

            String file = request.getParameter("fileName");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + file + "\"");
            response.setContentType("APPLICATION/OCTET-STREAM");
            outStream = response.getOutputStream();

            int len;
            byte[] buffer = new byte[1024];
            while ((len = istream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            outStream.flush();
            outStream.close();
            istream.close();

            long size = remoteFile.getContent().getSize();
            success = remoteFile.exists() && size == remoteFile.getContent().getSize();
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            manager.close();
        }
    }
public String createConnectionString(String remoteFilePath) {
        return "sftp://" + this.username + ":" + this.password + "@" + hostName + "/" + remoteFilePath;
}

1 个答案:

答案 0 :(得分:0)

原来,openSSH正在下载文件部分。每次尝试下载文件时都会丢失一些字节。 我用freeSSHd替换了openSSH,它解决了这个问题。