美文网首页
ftp和sftp上传和下载

ftp和sftp上传和下载

作者: 墨色尘埃 | 来源:发表于2018-02-04 21:25 被阅读22次

    AttachmentControl

    @RestController
    @RequestMapping("/v1/attachment")
    public class AttachmentControl {
        @Autowired
        private AttachmentMapper attachmentMapper;
        @Autowired
        private FtpConfig ftpConfig;
    
        public ResponseObj<List<Attachment>> list(@RequestParam String approvalId) {
            List<Attachment> list = attachmentMapper.list(approvalId);
            return new ResponseObj<>(list, RetCode.SUCCESS);
        }
    
        @RequestMapping(value = "", method = RequestMethod.POST)
        public ResponseObj<List<Attachment>> upload(HttpServletRequest request) {
            String approvalId = null;
            String basePath = ftpConfig.getFtpOperativePath();
    
            String operator = request.getParameter("operator");
    
            Map map = upload2Ftp(approvalId, operator, basePath, request);
            List<Attachment> list = (List<Attachment>) map.get("attachments");
            boolean flag = (boolean) map.get("status");
    
            return new ResponseObj<>(list, flag ? RetCode.SUCCESS : RetCode.FAIL);
        }
    
        public boolean upload(String approvalId, String operator, String basePath, HttpServletRequest request) {
            Map map = upload2Ftp(approvalId, operator, basePath, request);
            return (boolean) map.get("status");
        }
    
        public Map upload2Ftp(String approvalId, String operator, String basePath, HttpServletRequest request) {
            int size = 0;
            List<Attachment> attachments = new ArrayList<>();
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> files = multipartRequest.getFiles("filePath");
                size = files.size();
                if (size > 0) {
                    //根据日期生成独立文件夹
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1;
                    int day = calendar.get(Calendar.DAY_OF_MONTH);
                    String dirName = year + (month < 10 ? "0" : "") + month + (day < 10 ? "0" : "") + day;
    
                    String host = ftpConfig.getFtpHost();
                    int port = ftpConfig.getFtpPort();
                    String userName = ftpConfig.getFtpUserName();
                    String password = ftpConfig.getFtpPassWord();
    
                    for (MultipartFile file : files) {
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    
                        String originalName = file.getOriginalFilename();//原始文件名
                        String fileName = uuid + "_" + originalName;//修改上传文件名
                        String fileType = originalName.substring(originalName.lastIndexOf(".") + 1);//获取文件类型
                        String filePath = basePath + "/" + dirName;
    
                        boolean flag = false;
                        int i = 0;
                        Attachment attachment = null;
                        try {
                            //上传FTP
                            InputStream ips = file.getInputStream();
                            flag = FtpUtil.uploadFile(host, port, userName, password, basePath, dirName, fileName, ips);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (flag) {//写入附件表
                            attachment = new Attachment();
                            attachment.setFileId(CommonUtil.getSysRef());
                            attachment.setApprovalId(approvalId);
                            attachment.setFileName(fileName);
                            attachment.setoFileName(originalName);
                            attachment.setFileType(fileType);
                            attachment.setFilePath(filePath);
                            attachment.setOperator(operator);
                            i = attachmentMapper.insertSelective(attachment);
                        }
                        if (flag && 1 == i) {
                            attachments.add(attachment);
                        }
                    }
                }
            }
    
            Map result = new HashMap();
            result.put("status", attachments.size() == size);
            result.put("attachments", attachments);
            return result;
        }
    
        @RequestMapping(value = "", method = RequestMethod.GET)
        public void fileDownload(@RequestParam String fileId, HttpServletResponse response) {
            Attachment attachment = attachmentMapper.selectByPrimaryKey(fileId);
    
            if (null != attachment) {
                String host = ftpConfig.getFtpHost();
                int port = ftpConfig.getFtpPort();
                String userName = ftpConfig.getFtpUserName();
                String password = ftpConfig.getFtpPassWord();
                String remotePath = attachment.getFilePath();
                String fileName = attachment.getFileName();
                String oFileName = attachment.getoFileName();
    
                try {
                    response.setContentType("application/octet-stream");
                    //设置文件名
                    response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(oFileName, "UTF-8"));
                    FtpUtil.downloadFile(host, port, userName, password, remotePath, fileName, response.getOutputStream());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        @RequestMapping(value = "/image", method = RequestMethod.GET)
        public void imageDisplay(@RequestParam String fileId, HttpServletResponse response) {
            Attachment attachment = attachmentMapper.selectByPrimaryKey(fileId);
    
            String host = ftpConfig.getFtpHost();
            int port = ftpConfig.getFtpPort();
            String userName = ftpConfig.getFtpUserName();
            String password = ftpConfig.getFtpPassWord();
            String remotePath = attachment.getFilePath();
            String fileName = attachment.getFileName();
    
            try {
                response.setContentType("image/jpeg");
                FtpUtil.downloadFile(host, port, userName, password, remotePath, fileName, response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @RequestMapping(value = "/del", method = RequestMethod.POST)
        public ResponseObj<Boolean> del(@RequestBody Map formData) {
            String fileIds = (String) formData.get("fileIds");
            int i = attachmentMapper.deleteByPrimaryKey(formData);
            int count = fileIds.split(",").length;
    
            if (count == i)
                return new ResponseObj<>(true, RetCode.SUCCESS);
            return new ResponseObj<>(false, RetCode.FAIL);
        }
    
        @RequestMapping(value = "/dels", method = RequestMethod.POST)
        public ResponseObj<Boolean> deleteByApprovalId(@RequestBody Map formData) {
            String approvalIds = (String) formData.get("approvalIds");
            int i = attachmentMapper.deleteByApprovalId(formData);
            int count = approvalIds.split(",").length;
    
            return new ResponseObj<>(true, RetCode.SUCCESS);
        }
    
    
    }
    

    FtpConfig

    @Component
    @ConfigurationProperties(prefix = "pathconfig")
    @EnableConfigurationProperties({FtpConfig.class})
    public class FtpConfig {
    
        private String ftpHost;
        private int ftpPort;
        private String ftpUserName;
        private String ftpPassWord;
        private String ftpOperativePath;
        private String ftpCloudPath;
        private String ftpPortalPath;
        private String ftpMobilePath;
        private String ftpPropertyPath;
    
        public String getFtpHost() {
            return ftpHost;
        }
    
        public void setFtpHost(String ftpHost) {
            this.ftpHost = ftpHost;
        }
    
        public int getFtpPort() {
            return ftpPort;
        }
    
        public void setFtpPort(int ftpPort) {
            this.ftpPort = ftpPort;
        }
    
        public String getFtpUserName() {
            return ftpUserName;
        }
    
        public void setFtpUserName(String ftpUserName) {
            this.ftpUserName = ftpUserName;
        }
    
        public String getFtpPassWord() {
            return ftpPassWord;
        }
    
        public void setFtpPassWord(String ftpPassWord) {
            this.ftpPassWord = ftpPassWord;
        }
    
        public String getFtpOperativePath() {
            return ftpOperativePath;
        }
    
        public void setFtpOperativePath(String ftpOperativePath) {
            this.ftpOperativePath = ftpOperativePath;
        }
    
        public String getFtpCloudPath() {
            return ftpCloudPath;
        }
    
        public void setFtpCloudPath(String ftpCloudPath) {
            this.ftpCloudPath = ftpCloudPath;
        }
    
        public String getFtpPortalPath() {
            return ftpPortalPath;
        }
    
        public void setFtpPortalPath(String ftpPortalPath) {
            this.ftpPortalPath = ftpPortalPath;
        }
    
        public String getFtpMobilePath() {
            return ftpMobilePath;
        }
    
        public void setFtpMobilePath(String ftpMobilePath) {
            this.ftpMobilePath = ftpMobilePath;
        }
    
        public String getFtpPropertyPath() {
            return ftpPropertyPath;
        }
    
        public void setFtpPropertyPath(String ftpPropertyPath) {
            this.ftpPropertyPath = ftpPropertyPath;
        }
    }
    

    配置文件

    pathconfig:
      ftpHost: 172.16.11.66
      ftpPort: 21
      ftpUserName: sys
      ftpPassWord: SYS!!@@
      ftpOperativePath: YY
      ftpCloudPath: QYY
      ftpPortalPath: MH
      ftpMobilePath: MOBILE
      ftpPropertyPath: WY
    
    

    FtpUtil

    public class FtpUtil {
    
        /**
         * Description: 向FTP服务器上传文件
         *
         * @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
         */
        public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                         String filePath, String filename, InputStream input) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
    
            try {
                int reply;
    
                ftp.connect(host, port);// 连接FTP服务器
                // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
                ftp.login(username, password);// 登录
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                //切换到上传目录
                if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                    //如果目录不存在创建目录
                    String[] dirs = filePath.split("/");
                    String tempPath = basePath;
                    for (String dir : dirs) {
                        if (null == dir || "".equals(dir)) continue;
                        tempPath += "/" + dir;
                        if (!ftp.changeWorkingDirectory(tempPath)) {
                            if (!ftp.makeDirectory(tempPath)) {
                                return result;
                            } else {
                                ftp.changeWorkingDirectory(tempPath);
                            }
                        }
                    }
                }
                //设置上传文件的类型为二进制类型
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                //上传文件
                if (!ftp.storeFile(new String(filename.getBytes("GBK"), "iso-8859-1"), input)) {
                    return result;
                }
                input.close();
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } 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
         */
        public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                           String fileName, String localPath) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);
                // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
                ftp.login(username, password);// 登录
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
                FTPFile[] fs = ftp.listFiles();
                for (FTPFile ff : fs) {
                    String f = new String(ff.getName().getBytes("ISO-8859-1"), "GBK");
    
                    if (f.equals(fileName)) {
                        String[] split = f.split("_");
                        File localFile = new File(localPath + "/" + split[1]);
    
                        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;
        }
    
        /**
         * Description: 从FTP服务器下载文件
         *
         * @param host       FTP服务器hostname
         * @param port       FTP服务器端口
         * @param username   FTP登录账号
         * @param password   FTP登录密码
         * @param remotePath FTP服务器上的相对路径
         * @param fileName   要下载的文件名
         * @param ops        下载后保存到本地的路径
         * @return
         */
        public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                           String fileName, OutputStream ops) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);
                // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
                ftp.login(username, password);// 登录
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
                FTPFile[] fs = ftp.listFiles();
                for (FTPFile ff : fs) {
                    String f = new String(ff.getName().getBytes("ISO-8859-1"), "GBK");
    
                    if (f.equals(fileName)) {
                        ftp.retrieveFile(ff.getName(), ops);
                        ops.close();
                    }
                }
    
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
    
    }
    

    SFTPUtil

    public class SFTPUtil {
    
        /**
         * 默认端口
         */
        private final static int DEFAULT_PORT = 22;
    
        private final static String HOST = "host";
    
        private final static String PORT = "port";
    
        private final static String USER_NAME = "userName";
    
        private final static String PASSWORD = "password";
    
    
        /**
         * 服务端保存的文件名
         */
        private String remote;
    
        /**
         * 服务端保存的路径
         */
        private String remotePath;
    
        /**
         * 本地文件
         */
        private File local;
    
        /**
         * 主机地址
         */
        private String host;
    
        /**
         * 端口
         */
        private int port = DEFAULT_PORT;
    
        /**
         * 登录名
         */
        private String userName;
    
        /**
         * 登录密码
         */
        private String password;
    
        private ChannelSftp sftp;
    
    
        public SFTPUtil(String host, int port, String userName, String password) {
            this.init(host, port, userName, password);
        }
    
    
        /**
         * 初始化
         *
         * @param host
         * @param port
         * @param userName
         * @param password
         * @author 唐延波
         * @date 2015-6-23
         */
        private void init(String host, int port, String userName, String password) {
            this.host = host;
            this.port = port;
            this.userName = userName;
            this.password = password;
        }
    
        /**
         * 连接sftp
         *
         * @throws JSchException
         * @author 唐延波
         * @date 2015-6-23
         */
        private void connect() throws JSchException, NoSuchFieldException, IllegalAccessException, SftpException {
            JSch jsch = new JSch();
            // 取得一个SFTP服务器的会话
            Session session = jsch.getSession(userName, host, port);
            // 设置连接服务器密码
            session.setPassword(password);
            Properties sessionConfig = new Properties();
            // StrictHostKeyChecking
            // "如果设为"yes",ssh将不会自动把计算机的密匙加入"$HOME/.ssh/known_hosts"文件,
            // 且一旦计算机的密匙发生了变化,就拒绝连接。
            sessionConfig.setProperty("StrictHostKeyChecking", "no");
            // 设置会话参数
            session.setConfig(sessionConfig);
            // 连接
            session.connect();
            // 打开一个sftp渠道
            Channel channel = session.openChannel("sftp");
            sftp = (ChannelSftp) channel;
            channel.connect();
    
            Class cl = ChannelSftp.class;
            Field f =cl.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(sftp, 2);
            sftp.setFilenameEncoding("GBK");
    
    
    
        }
    
        /**
         * 上传文件
         *
         * @author 唐延波
         * @date 2015-6-23
         */
        public void uploadFile() throws Exception {
            FileInputStream inputStream = null;
            try {
                connect();
                if (isEmpty(remote)) {
                    remote = local.getName();
                }
                if (!isEmpty(remotePath)) {
                    sftp.cd(remotePath);
                }
                inputStream = new FileInputStream(local);
                sftp.put(inputStream, remote);
            } catch (Exception e) {
                throw e;
            } finally {
                sftp.disconnect();
                close(inputStream);
            }
        }
    
    
        public void uploadFile(InputStream inputStream) throws Exception {
            try {
                connect();
                if (isEmpty(remote)) {
                    remote = local.getName();
                }
                if (!isEmpty(remotePath)) {
                    createDir(remotePath);
                }
    
                sftp.put(inputStream, remote);
            } catch (Exception e) {
                throw e;
            } finally {
                sftp.disconnect();
                close(inputStream);
            }
        }
    
        public boolean isDirExist(String directory) throws Exception {
            boolean isDirExistFlag = false;
            try {
                SftpATTRS sftpATTRS = sftp.lstat(directory);
                isDirExistFlag = true;
                return sftpATTRS.isDir();
            } catch (Exception e) {
                if (e.getMessage().toLowerCase().equals("no such file")) {
                    isDirExistFlag = false;
                }
            }
            return isDirExistFlag;
        }
    
        public void createDir(String createpath) throws Exception {
            try {
                if (isDirExist(createpath)) {
                    this.sftp.cd(createpath);
                } else {
                    String pathArry[] = createpath.split("/");
    
                    for (String path : pathArry) {
                        if (path.equals("")) {
                            continue;
                        }
    
                        if (isDirExist(path.toString())) {
                            sftp.cd(path.toString());
                        } else {
                            // 建立目录
                            sftp.mkdir(path.toString());
                            // 进入并设置为当前目录
                            sftp.cd(path.toString());
                        }
                    }
    
                }
            } catch (SftpException e) {
                throw new Exception("创建路径错误:" + createpath);
            }
        }
    
        /**
         * 下载
         *
         * @author 唐延波
         * @date 2015-6-23
         */
        public void download() throws Exception {
            FileOutputStream output = null;
            try {
                this.connect();
                if (null != remotePath || !("".equals(remotePath))) {
                    sftp.cd(remotePath);
                }
                output = new FileOutputStream(local);
                sftp.get(remote, output);
            } catch (Exception e) {
                throw e;
            } finally {
                sftp.disconnect();
                close(output);
            }
        }
    
    
        public void download(OutputStream outputStream) throws Exception {
    
            try {
                this.connect();
                if (null != remotePath || !("".equals(remotePath))) {
                    sftp.cd(remotePath);
                }
                sftp.get(remote, outputStream);
            } catch (Exception e) {
                throw e;
            } finally {
                sftp.disconnect();
            }
        }
    
        public static boolean isEmpty(String str) {
            if (null == str || "".equals(str)) {
                return true;
            }
            return false;
        }
    
        public static void close(OutputStream... outputStreams) {
            for (OutputStream outputStream : outputStreams) {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public static void close(InputStream... inputStreams) {
            for (InputStream inputStream : inputStreams) {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public void setRemote(String remote) {
            this.remote = remote;
        }
    
        public void setRemotePath(String remotePath) {
            this.remotePath = remotePath;
        }
    
        public void setLocal(File local) {
            this.local = local;
        }
    
    
    }
    

    相关文章

      网友评论

          本文标题:ftp和sftp上传和下载

          本文链接:https://www.haomeiwen.com/subject/czdvzxtx.html