码迷,mamicode.com
首页 > Web开发 > 详细

jsch上传(基于sftp协议)

时间:2017-04-10 15:00:10      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:extend   tac   资源   err   config   tools   ssh   ring   parse   

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协议)

标签:extend   tac   资源   err   config   tools   ssh   ring   parse   

原文地址:http://www.cnblogs.com/kuma-naya/p/6688667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!