Jolly

附件上传至FTP和从FTP下载的代码
之前用java做过福建上传ftp和从ftp下载文件的功能,这里做一下记录。
扫描右侧二维码阅读全文
04
2017/10

附件上传至FTP和从FTP下载的代码

之前用java做过福建上传ftp和从ftp下载文件的功能,这里做一下记录。

/以下为附件上传至FTP和从FTP下载的代码*/


/**  
* Description: 向SFTP服务器上传文件  
* @param host FTP服务器hostname  
* @param port FTP服务器端口  
* @param username FTP登录账号  
* @param password FTP登录密码  
* @param basePath FTP服务器基础目录 
* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为
* basePath+filePath 
* @param filename 上传到FTP服务器上的文件名  
* @param input 输入流  
* @return 成功返回true,否则返回false  
* @throws Exception 
* @author jolly    2017-12-1
*/    
public static boolean uploadFileToSFTP(String filename, HttpServletRequest request) throws Exception {  
    boolean result = false;  
    FTPClient ftp = new FTPClient();  
    Properties prop = new Properties();
    ResourceBundle resource = ResourceBundle
        .getBundle("tellhow/actions/ftp");// 读取ftp配置文件
    String host = resource.getString("HOST");
    int port = Integer.parseInt(resource.getString("PORT"));
    String username = resource.getString("USERNAME");
    String password = resource.getString("PASSWORD");
    String filePath = resource.getString("FILEPATH");
    String localPath = request.getRealPath("/WebRoot/WEB-INF/upload/");
    try {  
        int reply;  
        ftp.connect(host, port);// 连接FTP服务器  
        // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器  
        boolean b = ftp.login(username, password);// 登录  
        if(!b){
            throw new Exception("登陆FTP不成功!");
        }
        reply = ftp.getReplyCode();  
        if (!FTPReply.isPositiveCompletion(reply)) {  
            ftp.disconnect();  
            return result;  
        }  
        File file = new File(localPath+filename);
        InputStream input = new FileInputStream(file);
        boolean t = ftp.changeWorkingDirectory(encoding(filePath));
        if(!t){
            ftp.mkd(encoding(filePath));
            ftp.changeWorkingDirectory(encoding(filePath));
        }
        //设置上传文件的类型为二进制类型  
        //ftp.setFileType(FTP.BINARY_FILE_TYPE);  
        boolean b2 = ftp.storeFile(encoding(filename), input);
        input.close();
        ftp.logout();
        if(!b2){
            throw new Exception("上传文件不成功!"); 
        }
        result = true;  
    } catch (IOException e) {  
        e.printStackTrace();  
        throw new Exception("未能连接上Ftp服务器!");
    } finally {  
        if (ftp.isConnected()) {  
            try {  
                ftp.disconnect();  
            } catch (IOException ioe) {  
            }  
        } 
    }  
    return result;  
}  

/**  
* Description: 从FTP服务器下载文件  
* @param host FTP服务器hostname  
* @param port FTP服务器端口  
* @param username FTP登录账号  
* @param password FTP登录密码  
* @param remotePath FTP服务器上的相对路径  
* @param fileName 要下载的文件名  
* @param localPath 下载后保存到本地的路径  
* @return  
* @author jolly    2017-12-1
* @throws Exception 
*/    
public static boolean downloadFileFromFTP(String fileName, HttpServletRequest request) throws Exception {  
    boolean result = false;  
    FTPClient ftp = new FTPClient();  
    Properties prop = new Properties();
    ResourceBundle resource = ResourceBundle
        .getBundle("tellhow/actions/ftp");// 读取ftp配置文件
    String host = resource.getString("host");
    int port = Integer.parseInt(resource.getString("PORT"));
    String username = resource.getString("USERNAME");
    String password = resource.getString("PASSWORD");
    String basePath = resource.getString("BASEPATH");
    String filePath = resource.getString("FILEPATH");
    String remotePath = resource.getString("REMOTEPATH");
    String localPath = request.getRealPath("/WebRoot/WEB-INF/upload");
    try {  
        int reply;  
        ftp.connect(host, port);  
        // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器  
        boolean b = ftp.login(username, password);// 登录  
        if(!b){
            throw new Exception("登陆FTP不成功!");
        }
        reply = ftp.getReplyCode();  
        if (!FTPReply.isPositiveCompletion(reply)) {  
            ftp.disconnect();  
            return result;  
        }  
        ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  
        FTPFile[] fs = ftp.listFiles();  
        for (FTPFile ff : fs) {  
            if (ff.getName().equals(fileName)) {  
                File localFile = new File(localPath + "/" + ff.getName());  

                OutputStream is = new FileOutputStream(localFile);  
                ftp.retrieveFile(ff.getName(), is);  
                is.close();  
            }  
        }  

        ftp.logout();  
        result = true;  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        if (ftp.isConnected()) {  
            try {  
                ftp.disconnect();  
            } catch (IOException ioe) {  
            }  
        }  
    }  
    return result;  
} 


/**
* 编码转换
* @param obj
* @return
*/
private static String encoding(Object obj){
    try{
        if(obj==null)
            return "";
        else
            return new String(obj.toString().getBytes("GBK"),"ISO-8859-1");
    }catch(Exception e){
        e.printStackTrace();
    }
    return ""; 
}

//删除文件,用于ftp上传完后删除本地临时文件夹文件
public void delFolder(String folderPath) {
    try {
        delAllFile(folderPath); // 删除完里面所有内容
    } catch (Exception e) {
        e.printStackTrace();
    }
}
// 删除指定文件夹下所有文件
// param path 文件夹完整绝对路径
public boolean delAllFile(String path) {
    boolean flag = false;
    File file = new File(path);
    if (!file.exists()) {
        return flag;
    }
    if (!file.isDirectory()) {
        return flag;
    }
    String[] tempList = file.list();
    File temp = null;
    for (int i = 0; i < tempList.length; i++) {
        if (path.endsWith(File.separator)) {
            temp = new File(path + tempList[i]);
        } else {
            temp = new File(path + File.separator + tempList[i]);
        }
        if (temp.isFile()) {
            temp.delete();
        }
        if (temp.isDirectory()) {
            delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
            flag = true;
        }
    }
    return flag;
}

public class SFTPConstants {
    public static final String SFTP_REQ_HOST = "host";
    public static final String SFTP_REQ_PORT = "port";
    public static final String SFTP_REQ_USERNAME = "username";
    public static final String SFTP_REQ_PASSWORD = "password";
    public static final int SFTP_DEFAULT_PORT = 22;
    public static final String SFTP_REQ_LOC = "location";
}
Last modification:November 25th, 2019 at 05:05 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment

🌓