将指定路径的文件上传到ftp上

package com.grandteach.ftpservice.controller;

import com.grandteach.ftpservice.common.R;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.io.File.separator;

@RequestMapping("/api/v1/upload")
@RestController //controller里面的方法都以json格式输出
public class FTPClientUtils {
    Log log = LogFactory.getLog(FTPClientUtils.class);

    @Value("${ftp.username}")
    private String userName;

    @Value("${ftp.password}")
    private String passWord;

    @Value("${ftp.ip}")
    private String ip;

    @Value("${ftp.port}")
    private int port;

    @Value("${web.ftpupload-path}")
    private String ftplocation;
    // ftp客户端
    private FTPClient ftpClient = new FTPClient();

    /**
     *
     * 功能:上传文件附件到文件服务器
     * @param //buffIn:上传文件流
     * @param //fileName:保存文件名称
     * @param //needDelete:是否同时删除
     * @return
     * @throws //IOException
     */
    @RequestMapping("/uploadFileInter")
    R uploadFileInter(HttpServletRequest request,HttpServletResponse response) throws FTPConnectionClosedException, IOException,Exception {
        response.setHeader("Access-Control-Allow-Origin","*");
        List<Map<String ,String>> list=new ArrayList<Map<String ,String>>();
        String cbfbm = request.getParameter("cbfbm");
        String taskid = request.getParameter("taskid");
        String ywxh = request.getParameter("ywxh");
        // 文件路径
        String ftpPath = cbfbm.substring(0,6) +separator+ cbfbm.substring(0,9)+separator+cbfbm.substring(0,12)+separator+cbfbm.substring(0,14)+separator+cbfbm+separator+ywxh;
        String CURRENT_DIR = "/"+ftpPath;

        if(cbfbm==null||"".equals(cbfbm)){
            return R.error("没有填写承包方编码!");
        }

        String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if (path.indexOf("file:")>-1){
            path = path.split("file:")[1];
        }
        File curAllInOneProjectFile = new File(path);
        File rootProjectFileDir = curAllInOneProjectFile.getParentFile().getParentFile().getParentFile().getParentFile();//获取上一级目录
        System.out.println("path:"+rootProjectFileDir.getPath());
        //rootProjectFileDir.getPath()
        String njqpath = ftplocation+separator+"data"+separator+"doc"+separator+"blobstore"+separator+"YWDOC"+separator+taskid;
        File dirFile = new File(njqpath);
        //判断该文件或目录是否存在,不存在时在控制台输出提醒
        if (!dirFile.exists()) {
            System.out.println("do not exit");
            return R.error("do not exit!"+njqpath);
        }

        //获取此目录下的所有文件名与目录名
        String[] fileList = dirFile.list();

        //String fileName = multipartFiles.get(0).getOriginalFilename();
        //InputStream buffIn = multipartFiles.get(0).getInputStream();
        boolean needDelete = false;
        FileInputStream buffIn =null;
        // 上传文件
        try {
            if (fileList.length==0){
                System.out.println("file is not exit");
                return R.error("文件:file is not exit!");
            }
            for (int i = 0; i < fileList.length; i++){
                Map<String, String> map = new HashMap<>();
                //遍历文件目录
                String fileName = fileList[i];
                buffIn  = new FileInputStream(njqpath+separator+fileName);
                // 获取上传到ftp前的文件大小
                int localSize = buffIn.available();
                // 建立连接
                connectToServer();
                // 设置传输二进制文件
                setFileType(FTP.BINARY_FILE_TYPE);
                int reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    throw new IOException("failed to connect to the FTP Server:" + ip);
                }
                ftpClient.enterLocalPassiveMode();
                // 判断是否有对应的目录
                if (!ftpClient.changeWorkingDirectory(CURRENT_DIR)) {
                    // 创建目录
                    ftpClient.makeDirectory("/" + CURRENT_DIR);
                }
                // 上传文件到ftp
                ftpClient.setControlEncoding("UTF-8");
                boolean returnValue = ftpClient.storeFile(new String((CURRENT_DIR + separator + fileName).getBytes("UTF-8"), "iso-8859-1"), buffIn);
                // 上传到ftp前的文件和已经上传到ftp的文件比较大小
                int ftpSize = 0;
                for (int y=0;y<ftpClient.listFiles().length;y++){
                    if(ftpClient.listFiles()[y].getName().equals(fileName)){
                        ftpSize = (int)ftpClient.listFiles()[y].getSize();
                        break;
                    }
                }
               if (ftpSize != localSize) {
                    uploadFileInter(request,response);
                }
                if (needDelete) {
                    ftpClient.deleteFile(fileName);
                }
                map.put("FILENAME",fileName);
                map.put("FILEPATH", "\\"+ftpPath);
                map.put("SFTPPORT",String.valueOf(port));
                map.put("SFTPIP",ip);
                list.add(map);
                // 输出操作结果信息
                if (returnValue) {
                    log.info("uploadToFtp INFO: upload file  to ftp : succeed!");
                } else {
                    log.info("uploadToFtp INFO: upload file  to ftp : failed!");
                }
            }
            buffIn.close();

            // 关闭连接
            closeConnect();
            //return R.data("操作成功");

            } catch (FTPConnectionClosedException e) {
                log.error("ftp连接被关闭!", e);
                throw e;
            } catch (Exception e) {
                log.error("ERR : upload file  to ftp : failed! ", e);
                throw e;
            } finally {
                try {
                    if (buffIn != null) {
                        buffIn.close();
                    }
                } catch (Exception e) {
                    log.error("ftp关闭输入流时失败!", e);
                    return R.error(e.getMessage());
                }
                if (ftpClient.isConnected()) {
                    closeConnect();
                    //return R.data("操作成功");
                }
            return R.data(list);
            }

    }

    /**
     * 设置传输文件的类型[文本文件或者二进制文件]
     *
     * @param fileType
     *            --BINARY_FILE_TYPE、ASCII_FILE_TYPE
     */
    private void setFileType(int fileType) {
        try {
            ftpClient.setFileType(fileType);
        } catch (Exception e) {
            log.error("ftp设置传输文件的类型时失败!", e);
        }
    }

    /**
     *
     * 功能:关闭连接
     */
    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            log.error("ftp连接关闭失败!", e);
        }
    }

    /**
     * 连接到ftp服务器
     */
    private void connectToServer() throws FTPConnectionClosedException,Exception {
        if (!ftpClient.isConnected()) {
            int reply;
            try {
                ftpClient=new FTPClient();
                ftpClient.connect(ip,port);
                ftpClient.login(userName,passWord);
                reply = ftpClient.getReplyCode();

                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    log.info("connectToServer FTP server refused connection.");
                }

            }catch(FTPConnectionClosedException ex){
                log.error("服务器:IP:"+ip+"没有连接数!there are too many connected users,please try later", ex);
                throw ex;
            }catch (Exception e) {
                log.error("登录ftp服务器【"+ip+"】失败", e);
                throw e;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值