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