ftp 下载

来源:互联网 发布:java tomcat 编辑:程序博客网 时间:2024/04/30 07:40
import org.apache.commons.net.ftp.FTPClient;
/**
*
*   ftp文件下载
* @throws Exception 

*/

@GetMapping("/download")
public void download(HttpServletResponse response) throws Exception { 

String hostname="136.219.100.213";
Integer port=21;
String username="shop";
String password="000";
String remotePath="/upload/file/201710";//相对路径   /upload/image/201710
String filename="2017032211.pdf";

FTPClient ftp= new FTPClient();

ftp.connect(hostname, port);// 连接FTP服务器   如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登录ftp
ftp.setControlEncoding("UTF-8"); // 设置字符编码
ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // 设置文件传输格式
ftp.enterLocalPassiveMode();//防止端口没有开启
int reply = ftp.getReplyCode();// 以2开头的都表示登陆成功
if (FTPReply.isPositiveCompletion(reply)) {
// 转到指定下载目录
if (!ftp.changeWorkingDirectory(remotePath)) {
String[] paths = StringUtils.split(remotePath, "/");
String p = "/";
ftp.changeWorkingDirectory(p);
for (String s : paths) {
p += s + "/";
if (!ftp.changeWorkingDirectory(p)) {
ftp.makeDirectory(s);
ftp.changeWorkingDirectory(p);
}
}
}
FTPFile[] listFiles = ftp.listFiles();//列出所有的文件
for (FTPFile ftpFile: listFiles ) {
if (ftpFile.getName().equals(filename)) {
if (ftpFile.isFile()) {

//根据文件名下载FTP服务器上的文件  

//第一种触发浏览器下载
InputStream ins=ftp.retrieveFileStream(ftpFile.getName());  
                ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
        byte[] buf = new byte[1024];  
        int bufsize = 0;  
        while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {  
            byteOut.write(buf, 0, bufsize);  
       }  
        byte[] buffer = byteOut.toByteArray();  
        byteOut.close();  
        ins.close();  

        String fileSuffixName=   filename.substring(filename.lastIndexOf(".")+1);
       
response.reset(); //清除缓存
        response.setContentType("application/" +fileSuffixName + ";" +"charset = UTF-8"); //设置字符集和文件后缀名
        response.setHeader("Content-Disposition","attachment; filename=" +filename); // 设置文件名称
       
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
        toClient.write(buffer);  
        toClient.flush();  
        toClient.close();  

//第二种下载到指定目录
        String localPath="D:"+File.separator+"program_file"+File.separator+"FTP_file";//"D:"+File.separator+"program_file"+File.separator+"FTP_file";
        File lFile = new File(localPath);
lFile.mkdir(); // 如果文件所在的文件夹不存在就创建
FileOutputStream fos = new FileOutputStream(localPath+File.separator+filename);
ftp.retrieveFile(ftpFile.getName(), fos);
fos.flush(); // 将缓冲区中的数据全部写出
fos.close(); // 关闭流
}
}

ftp.logout();// 退出ftp
if (ftp.isConnected()) {
ftp.disconnect();
}
} else{
ftp.disconnect();
}


}
原创粉丝点击