ftp上传工具类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yjaspire/article/details/83270955

pom

 	<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>

代码如下

package fs.basecore.utils;



import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;





/**
 * ftp工具类
 * @author jun
 *完整路径
 *
 */
public class FtpUtil {
	//通过properties文件自动注入
    @Value("${ftp.host}")
    private  String host;    //ftp服务器ip
    @Value("${ftp.port}")
    private  int port;        //ftp服务器端口
    @Value("${ftp.username}")
    private  String username;//用户名
    @Value("${ftp.password}")
    private  String password;//密码
    @Value("${ftp.fileBasePath}")
    private  String fileBasePath;//存放文件的基本路径
    @Value("${ftp.imageBasePath}")
    private String imageBasePath;//存放图片的基本路径
    
    //测试的时候把这个构造函数打开,设置你的初始值,然后在代码后面的main方法运行测试
    public FtpUtil() throws Exception {
        //System.out.println(this.toString());
        host="xx.xx.xx.xx";
        port=21;
        username="xxxx";
        password="xxxx";
        fileBasePath="/lcp/files";
        
        
    }
    /**
     * host+服务器项目根目录(根据图片或文件有区分)+业务类型代码文件+时间+名字
     * 如
     * ftp://xx.xx.xx.xx/lcp/images/good_images/20181017/2018101714573200096.png
     * ftp://xx.xx.xx.xx/lcp/files/good_file/20181017/2018101713380600090.pdf
     * 
     * @param path        上传文件存放在服务器的路径  /good_images/20181017/
     * @param filename    上传文件名  2018101714573200096.png
     * @param input        输入流
     * @param basePath     /lcp/images
     * @return
     */
    public  boolean fileUpload(String path,String filename,InputStream input,String basePath) {
    	
    	
		
        FTPClient ftp=new FTPClient();
     
        try {
            ftp.connect(host, port);
            ftp.login(username, password);
            //设置文件编码格式
            ftp.setControlEncoding("UTF-8");
            //ftp通信有两种模式
                //PORT(主动模式)客户端开通一个新端口(>1024)并通过这个端口发送命令或传输数据,期间服务端只使用他开通的一个端口,例如21
                //PASV(被动模式)客户端向服务端发送一个PASV命令,服务端开启一个新端口(>1024),并使用这个端口与客户端的21端口传输数据
                //由于客户端不可控,防火墙等原因,所以需要由服务端开启端口,需要设置被动模式
            ftp.enterLocalPassiveMode();
            //设置传输方式为流方式
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            //获取状态码,判断是否连接成功
            if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new RuntimeException("FTP服务器拒绝连接");
            }
            
           
            //转到上传文件的根目录
            if(!ftp.changeWorkingDirectory(basePath)) {
                throw new RuntimeException("根目录不存在,需要创建");
            }
            //判断是否存在目录
            if(!ftp.changeWorkingDirectory(path)) {
                String[] dirs=path.split("/");
                //创建目录
                for (String dir : dirs) {
                    if(null==dir||"".equals(dir)) continue;
                    //判断是否存在目录
                    if(!ftp.changeWorkingDirectory(dir)) {
                        //不存在则创建
                        if(!ftp.makeDirectory(dir)) {
                            throw new RuntimeException("子目录创建失败");
                        }
                        //进入新创建的目录
                        ftp.changeWorkingDirectory(dir);
                    }
                }
                //设置上传文件的类型为二进制类型
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                //上传文件
                if(!ftp.storeFile(filename, input)) {
                    return false;
                }
                input.close();
                ftp.logout();
                return true;
            }
            
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return false;
    }
    
    
    
    /**
     * 图片显示
     * @param filename    文件名,注意!此处文件名为加路径文件名,如:/good_images/20181017/2018101713392600092.jpg
     * @param baePath    /lcp/images
     * @return        
     */
    public Boolean binaryIo(String baePath,String filename,HttpServletResponse response) {
        FTPClient ftp=new FTPClient();
        InputStream inputStream =null;
        
        try {
            ftp.connect(host, port);
            ftp.login(username, password);
            //设置文件编码格式
            ftp.setControlEncoding("UTF-8");
            //ftp通信有两种模式
                //PORT(主动模式)客户端开通一个新端口(>1024)并通过这个端口发送命令或传输数据,期间服务端只使用他开通的一个端口,例如21
                //PASV(被动模式)客户端向服务端发送一个PASV命令,服务端开启一个新端口(>1024),并使用这个端口与客户端的21端口传输数据
                //由于客户端不可控,防火墙等原因,所以需要由服务端开启端口,需要设置被动模式
            ftp.enterLocalPassiveMode();
            //设置传输方式为流方式
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            //获取状态码,判断是否连接成功
            if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new RuntimeException("FTP服务器拒绝连接");
            }
            
            int index=filename.lastIndexOf("/");
            //获取文件的路径
            String path=filename.substring(0, index);
            //获取文件名
            String name=filename.substring(index+1);
            //判断是否存在目录
            if(!ftp.changeWorkingDirectory(baePath+path)) {
                throw new RuntimeException("文件路径不存在:"+baePath+path);
            }
            //获取该目录所有文件
            FTPFile[] files=ftp.listFiles();
            for (FTPFile file : files) {
                //判断是否有目标文件
                //System.out.println("文件名"+file.getName()+"---"+name);
                if(file.getName().equals(name)) {
                    //如果找到,将目标文件复制到本地
                	inputStream = ftp.retrieveFileStream(file.getName());
                     ServletOutputStream outputStream = response.getOutputStream();
                   //读取文件流
             		int len = 0;
             		byte[] buffer = new byte[1024 * 10];
             		while ((len = inputStream.read(buffer)) != -1){
             			outputStream.write(buffer,0,len);
             		}
             		outputStream.flush();
             		outputStream.close();
             		inputStream.close();
                  
                    
                }
               
            }
            ftp.logout();
            return  true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    
    /**
     * 下载
     * @param filename    文件名,注意!此处文件名为加路径文件名,如:/good_images/20181017/2018101714573200096.png
     * @param localPath    存放到本地第地址
     * @param  baePath    /lcp/images         
     */
    public boolean downloadFileWeb(String baePath,String filename,HttpServletResponse response) {
        FTPClient ftp=new FTPClient();
        try {
            ftp.connect(host, port);
            ftp.login(username, password);
            //设置文件编码格式
            ftp.setControlEncoding("UTF-8");
            //ftp通信有两种模式
                //PORT(主动模式)客户端开通一个新端口(>1024)并通过这个端口发送命令或传输数据,期间服务端只使用他开通的一个端口,例如21
                //PASV(被动模式)客户端向服务端发送一个PASV命令,服务端开启一个新端口(>1024),并使用这个端口与客户端的21端口传输数据
                //由于客户端不可控,防火墙等原因,所以需要由服务端开启端口,需要设置被动模式
            ftp.enterLocalPassiveMode();
            //设置传输方式为流方式
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            //获取状态码,判断是否连接成功
            if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new RuntimeException("FTP服务器拒绝连接");
            }
            
            int index=filename.lastIndexOf("/");
            //获取文件的路径
            String path=filename.substring(0, index);
            //获取文件名
            String name=filename.substring(index+1);
            //判断是否存在目录
            if(!ftp.changeWorkingDirectory(baePath+path)) {
                throw new RuntimeException("文件路径不存在:"+baePath+path);
            }
            //获取该目录所有文件
            FTPFile[] files=ftp.listFiles();
            for (FTPFile file : files) {
                //判断是否有目标文件
                //System.out.println("文件名"+file.getName()+"---"+name);
                if(file.getName().equals(name)) {
                    //如果找到,将目标文件复制到本地
                	 response.addHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"");
                     response.setHeader("Accept-Ranges", "bytes");
                    ServletOutputStream outputStream = response.getOutputStream() ;
                    ftp.retrieveFile(file.getName(), outputStream);
                    outputStream.flush();
                    outputStream.close();
                }
            }
            ftp.logout();
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    
    /**
     * 
     * @param filename    文件名,注意!此处文件名为加路径文件名,如:/2015/06/04/aa.jpg
     * @param localPath    存放到本地第地址
     * @return        
     */
    public boolean downloadFile(String baePath,String filename,String localPath) {
        FTPClient ftp=new FTPClient();
        try {
            ftp.connect(host, port);
            ftp.login(username, password);
            //设置文件编码格式
            ftp.setControlEncoding("UTF-8");
            //ftp通信有两种模式
                //PORT(主动模式)客户端开通一个新端口(>1024)并通过这个端口发送命令或传输数据,期间服务端只使用他开通的一个端口,例如21
                //PASV(被动模式)客户端向服务端发送一个PASV命令,服务端开启一个新端口(>1024),并使用这个端口与客户端的21端口传输数据
                //由于客户端不可控,防火墙等原因,所以需要由服务端开启端口,需要设置被动模式
            ftp.enterLocalPassiveMode();
            //设置传输方式为流方式
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            //获取状态码,判断是否连接成功
            if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new RuntimeException("FTP服务器拒绝连接");
            }
            
            int index=filename.lastIndexOf("/");
            //获取文件的路径
            String path=filename.substring(0, index);
            //获取文件名
            String name=filename.substring(index+1);
            //判断是否存在目录
            if(!ftp.changeWorkingDirectory(baePath+path)) {
                throw new RuntimeException("文件路径不存在:"+baePath+path);
            }
            //获取该目录所有文件
            FTPFile[] files=ftp.listFiles();
            for (FTPFile file : files) {
                //判断是否有目标文件
                //System.out.println("文件名"+file.getName()+"---"+name);
                if(file.getName().equals(name)) {
                    //System.out.println("找到文件");
                    //如果找到,将目标文件复制到本地
                    File localFile =new File(localPath+"/"+file.getName());
                    OutputStream out=new FileOutputStream(localFile);
                   
                    ftp.retrieveFile(file.getName(), out);
                    out.close();
                }
            }
            ftp.logout();
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    /**删除
     * filename文件相对路径
     * basePath  根路径 
     * @param filename
     * @param basePath
     * @return
     */
    public boolean deleteFile(String filename,String basePath) {
        FTPClient ftp=new FTPClient();
        try {
            ftp.connect(host, port);
            ftp.login(username, password);
            //设置编码格式
            ftp.setControlEncoding("UTF-8");
            ftp.enterLocalPassiveMode();
            //获取状态码,判断是否连接成功
            if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new RuntimeException("FTP服务器拒绝连接");
            }
            int index=filename.lastIndexOf("/");
            //获取文件的路径
            String path=filename.substring(0, index);
            //获取文件名
            String name=filename.substring(index+1);
            //判断是否存在目录,不存在则说明文件存在
            if(!ftp.changeWorkingDirectory(basePath+path)) {
                return true;
            }
            if(ftp.deleteFile(name)) {
                clearDirectory(ftp, basePath, path);
                ftp.logout();
                return true;
            }
            ftp.logout();
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    
    /**
     * 
     * @param ftp    
     * @param fileBasePath    
     * @param path        以path为根,递归清除上面所有空的文件夹,直到出现不为空的文件夹停止,最多清除到fileBasePath结束
     * @throws IOException
     */
    private void clearDirectory(FTPClient ftp,String fileBasePath,String path) throws IOException {
        //如果路径长度小于2,说明到顶了
        if(path.length()<2) {
            return ;
        }
        //如果当前目录文件数目小于1则删除此目录
        if(ftp.listNames(fileBasePath+path).length<1) {
            //删除目录
            System.out.println("删除目录:"+fileBasePath+path);
            ftp.removeDirectory(fileBasePath+path);
            int index=path.lastIndexOf("/");
            //路径向上一层
            path=path.substring(0, index);
            //继续判断
            clearDirectory(ftp, fileBasePath, path);
        }
    }
    
    //两个功能其中一个使用的话另一个需要注释
    public static void main(String []args) throws Exception   {
    	
    	 FtpUtil ftputil=new FtpUtil();
   	 boolean downloadFile = ftputil.deleteFile("/2018/10/16/2018101608342700047.png", "/lcp/images");
   	 
       
    	LocalDateTime  locTime=LocalDateTime.now();
    	DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
    	double random = Math.random();
    	System.out.println(random);
    	String format = locTime.format(ofPattern);
System.out.println(format);
  
   
       
    }
    
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getfileBasePath() {
        return fileBasePath;
    }
    public void setfileBasePath(String fileBasePath) {
        this.fileBasePath = fileBasePath;
    }
    @Override
    public String toString() {
        return "FtpUtil [host=" + host + ", port=" + port + ", username=" + username + ", password=" + password
                + ", fileBasePath=" + fileBasePath + "]";
    }
}

猜你喜欢

转载自blog.csdn.net/yjaspire/article/details/83270955