首页 > 代码库 > jsch上传(基于sftp协议)

jsch上传(基于sftp协议)

public class FtpFileUpload extends BaseController {
    private ChannelSftp sftp = null;
    private Session sshSession = null;
    private Channel channel = null;
    
    /**
     * 连接sftp服务器
     * @return
     */
    public boolean connectFtpServer(String ip) {
        try {
            JSch jsch = new JSch();    
            sshSession = jsch.getSession(Const.USER, ip, Const.PORT);
            sshSession.setPassword(Const.PASSWORD);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp)channel;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    
    public Map<String, String> fileUpload(String pathName, HttpServletRequest request) {

        /**
         * 存放返回信息
         */
        Map<String,String> map = new HashMap<>();
        
        /**
         * 处理上传
         */
        
        if(!ServletFileUpload.isMultipartContent(request)) {
            map.put("error", "请选择要上传的文件!");
            return map;
        }
        
        if(!CommTool.checkStr(pathName)) {
            map.put("error", "文件目录名不可为空!");
            return map;
        }
        
        /**
         * 文件目录层次创建
         */
        String localPath = pathName + "/";
        if (!"temp".equals(pathName)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String ymd = format.format(new Date());
            localPath += ymd + "/";
        }
        
        /**
         * 最大文件大小
         */
        long maxSize = 1000000000;
        
        /**
         * 上传
         */
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        List<?> items = null;
        try {
            //若上传的文件是多个的话,设置键的标志
            int flag = 1;
            
            items = upload.parseRequest(request);
            Iterator<?> iterator = items.iterator();
            while(iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                String fileName = item.getName();
                
                if(!item.isFormField()) {
                    //文件大小检查
                    if(item.getSize() > maxSize) {
                        map.put("errorInfo", "上传文件大小超过限制!");
                        return map;
                    }
                    /*
                     * 检查扩展名
                     */
                    String fileExt = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                    
                    //将工作空间转移到相应的目录下
                    String[] folders = localPath.split("/");
                    for(String folder:folders) {
                        if(folder.length() > 0) {
                            try {
                                sftp.cd(folder);
                            } catch(SftpException e) {
                                try {
                                    sftp.mkdir(folder);
                                    sftp.cd(folder);
                                } catch (SftpException e1) {
                                    map.put("errorInfo", "服务器端文件夹操作错误");
                                    return map;
                                }
                            }
                        }
                    }
                    
                    //重新设置文件名称
                    String newFileName = YMDTools.currentTimestamp() + "." + fileExt;
                    //进行文件上传
                    try {
                        sftp.put(item.getInputStream(), newFileName);
                        
                        //读取Excel时返回的地址
                        String resultPath = Const.BASE_PATH + localPath + newFileName;
                        map.put("eUrl"+flag, resultPath);

                        flag++;
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        map.put("errorInfo", "写文件错误");
                    }
                    //文件上传完毕,工作目录回调,以便其他文件上传
                    for(int i=0; i<folders.length-1; i++) {
                        try {
                            sftp.cd("..");
                        } catch (SftpException e) {
                            map.put("errorInfo", "文件夹回调发生错误");
                            return map;
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            map.put("errorInfo", "接收文件异常!");
            return map;
        } finally {
            releaseResource();
        }
        
        return map;
    }
    
    /**
     * 释放资源
     * @param sftp
     * @param sshSession
     * @param channel
     */
    public void releaseResource() {
        if (channel != null) {
            channel.disconnect();
        }
        if (sshSession != null) {
            sshSession.disconnect();
        }
        if (sftp != null) {
            sftp.disconnect();
        }
    }
    
    /**
     * 删除文件
     * @param directory
     * @throws Exception
     */
    public void delete(String directory) { 
        int index = directory.lastIndexOf("/");
        String dir = directory.substring(0, index);
        String deleteFile = directory.substring(index + 1);
        System.out.println("dir  "+dir);
        System.out.println("deleteFile   "+ deleteFile);
        try {
            sftp.cd(dir);
            sftp.rm(deleteFile);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    } 
}

 

jsch上传(基于sftp协议)