我正在使用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;
}
答案 0 :(得分:0)
原来,openSSH正在下载文件部分。每次尝试下载文件时都会丢失一些字节。 我用freeSSHd替换了openSSH,它解决了这个问题。