1

I am using vfs2 to download file through sftp.

.txt and .xml files are downloading correctly, but .pdf files are downloading corrupted.

Below is my code:

Does anyone see what I am doing wrong?

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;
}
Angelina
  • 2,175
  • 10
  • 42
  • 82

1 Answers1

0

It turned out that openSSH was downloading file partial. Some bytes were missing each time I would try to download file. I replaced openSSH with freeSSHd and it fixed the issue.

Angelina
  • 2,175
  • 10
  • 42
  • 82