zoukankan      html  css  js  c++  java
  • Java上传图片到Ftp,包含上传后文件大小为0的问题和Properties配置文件的读取

    准备工作:需要使用coomos-net jar包。下载地址

    一、 上传图片到FTP,文件大小为0的问题,解决:将ftp模式修改为Passive模式就可以了。

    //将ftp模式修改为Passive模式
    ftpClient.enterLocalPassiveMode();

    二、配置文件的操作,具体介绍请看 Java中Properties类的用法总结

    1.使用.properties配置文件的形式定义相关常量。

     2.在工具类中导入配置文件

    private static Properties getFtpConfig(){
            Properties p=new Properties();
            String path=Thread.currentThread().getContextClassLoader().getResource("ftpConfig.properties").getPath();
            try {
              p.load(new FileInputStream(path));
    //          System.out.println(p.getProperty("ftpUsername"));
    //          System.out.println(p.getProperty("ftpPassword"));
    //          System.out.println(p.getProperty("ftpServerIP"));
    //          System.out.println(p.getProperty("basePath"));
              
            } catch (Exception e) {
              e.printStackTrace();
            } 
            return p;
          }
    Properties

    3.调用该方法,这样就取到了配置文件里对应的数据。

    private static String ftpUsername = getFtpConfig().getProperty("ftpUsername");
    private static String ftpPassword =getFtpConfig().getProperty("ftpPassword");
    private static String ftpServerIP=getFtpConfig().getProperty("ftpServerIP");
    private static String basePath  = getFtpConfig().getProperty("basePath");//    文件路径

    三、下面开始讲上传ftp具体的操作

    1.将前台传回的base64编码,进行拆分。 解码之前得去掉"data:image/jpeg;base64,"。

    String ftpImgSrc="";
    if (!("".equals(base64ImgsString)) && base64ImgsString !=null) {
          SimpleDateFormat dateFormatImg = new SimpleDateFormat("yyyyMMddHHmmss");
          List<Object> imgBase64List = JSON.parseArray(base64ImgsString);
          for (Object object : imgBase64List) {
            String[] imgBaseArray = object.toString().split(",");
            String base64Head = imgBaseArray[0];
            //图片后缀
           String imgSuffix = base64Head.substring(base64Head.indexOf("/")+1, base64Head.indexOf(";"));
            //去掉base64编码字符串的前缀
           String imgStr=imgBaseArray[1];
           //重命名图片文件,日期加工号
           String newImgName = dateFormatImg.format(new Date()) +"_"+zjmWorkNumber+"."+imgSuffix;
           //向FTP服务器上传文件 ,返回路径
           ftpImgSrc = FtpUtil.uploadFile("CZBG",newImgName,imgStr);
         }
    }

    2.上传文件方法,参数为项目名,图片名称,图片加密后的字符串。

    我的文件路径是ftp:/ftpIP//picture/大项目名/子项目名/yyyyMMdd/yyyyMMddHHmmss_xxx.jpg

     

    /**
         *  向FTP服务器上传文件 
         * @author Administrator
         * 2019年12月25日 下午1:45:34 
         * @param projectName 项目名
         * @param imgName 文件名
         * @param imgStr 图片码
         * @return 成功返回true,否则返回false 
         * @throws FileNotFoundException 
         */
        public static String uploadFile(String projectName,String imgName,String imgStr) throws FileNotFoundException {
            String result = "";
            FTPClient ftpClient = new FTPClient();
            String dfFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());//分日期存放:20191225
            //FTP服务器文件存放路径。
            String basePathProject = basePath +"/"+ projectName;
            try {
                int reply;
                // 连接FTP服务器,用默认端口直接连接FTP服务器
                ftpClient.connect(ftpServerIP);
                // 登录
                ftpClient.login(ftpUsername, ftpPassword);
                reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    System.out.println("连接ftp失败!");
                    return result;
                }
                //将ftp模式修改为Passive模式
                ftpClient.enterLocalPassiveMode();
                //新建相关的项目文件
                ftpClient.makeDirectory(basePathProject);
                //切换到对应项目文件夹下
                ftpClient.changeWorkingDirectory(basePathProject);
                //创建当前日期文件夹
                ftpClient.makeDirectory(dfFolder);
                //切换到上传目录
                ftpClient.changeWorkingDirectory(dfFolder);
                String filePath ="ftp:/"+ftpServerIP+basePathProject+"/"+dfFolder+"/"+imgName;
                //上传图片
                if (imgStr == null) //图像数据为空  
                    return result;  
                BASE64Decoder decoder = new BASE64Decoder();  
                try{  
                    //Base64解码  
                    byte[] b = decoder.decodeBuffer(imgStr); 
                    for(int i=0;i<b.length;++i){  
                        if(b[i]<0){//调整异常数据  
                            b[i]+=256;  
                        }  
                    }  
    //              //设置上传文件的类型为二进制类型
                    ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
                    InputStream is = null;
                    is = new ByteArrayInputStream(b);
                    ftpClient.storeFile(new String(imgName.getBytes("utf-8"), "iso-8859-1"), is);
                    is.close();
                    //退出
                    ftpClient.logout();
                    result = filePath;//返回存的ftp路径
                }catch (Exception e){
                    e.printStackTrace();
                    return result;  
                }  
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftpClient.isConnected()) {
                    try {
                        ftpClient.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
    FTP上传方法

    成功上传

     

     问题:表单提交时因为图片太大,Ajax发送请求,后台接收都为null。

    解决:修改tomcat  maxPostSize="-1" 使post内容大小不限制

    tomcat7.0.63之前的版本

    maxPostSize 设置为 0 或者负数

    Connector 节点中加入maxPostSize="0"  或者  maxPostSize="-1" 

    tomcat7.0.63之后的版本,需要设置为负数

    Connector 节点中加入 maxPostSize="-1" 

  • 相关阅读:
    不务正业系列-浅谈《过气堡垒》,一个RTS玩家的视角
    [LeetCode] 54. Spiral Matrix
    [LeetCode] 40. Combination Sum II
    138. Copy List with Random Pointer
    310. Minimum Height Trees
    4. Median of Two Sorted Arrays
    153. Find Minimum in Rotated Sorted Array
    33. Search in Rotated Sorted Array
    35. Search Insert Position
    278. First Bad Version
  • 原文地址:https://www.cnblogs.com/sweetC/p/12163361.html
Copyright © 2011-2022 走看看