我有添加附件的功能。当我们附加任何文件时,它被上传到FTP服务器。为了查看目的,有一个链接显示浏览器本身内FTP服务器的文件内容。从FTP服务器下载后我可以打开文件,但我不想在本地机器上下载或保存文件。有没有办法从FTP服务器打开文件而无需下载或保存在本地机器上?
我写的代码。
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpServerIp);
boolean connectionStatus = ftpClient.login(ftpServerUserName, ftpServerPassword);
if(connectionStatus){
log.info("Connected successfully.");
}
ftpClient.changeWorkingDirectory(ftpServerUploadPath);
fos = new FileOutputStream(fileName);
boolean result = ftpClient.retrieveFile(fileName, fos);
log.info("result==>"+result);
此处检索文件时结果为true
。但我无法显示文件内容。有没有办法实现它?
任何帮助表示赞赏。提前谢谢。
答案 0 :(得分:0)
我使用下面的代码解决了这个问题。
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpServerIp);
boolean connectionStatus = ftpClient.login(ftpServerUserName, ftpServerPassword);
if(connectionStatus){
log.info("Connected successfully.");
}
ftpClient.changeWorkingDirectory(ftpServerUploadPath);
InputStream stream = ftpClient.retrieveFileStream(fileName);
int length = 0;
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType( fileName );
response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
response.setHeader( "Content-Disposition", "attachment; filename=\"" + fileName + "\"" );
byte[] bbuf = new byte[fileName.length()];
DataInputStream in = new DataInputStream(stream);
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
out.write(bbuf,0,length);
}
in.close();
out.flush();
out.close();