关于本地服务器存文件目录成功与服务器存文件目录不成功的问题。
//将获取的base64字符串 转换成字节数组 Base64 encoder = new Base64(); byte[] decode = encoder.decode(imageBase64); //获取项目临时图片文件夹 String realpath = ServletActionContext.getServletContext().getRealPath("/tmp/"); //如果不存在则自行创建 if (!new File(realpath).exists()) { new File(realpath).mkdir(); } //以点号分割文件名 并截取文件类型名 如果不存在的话 则默认为jpg // String[] imageNameSplit = imageName.split("\\."); // String imageType = imageNameSplit.length > 1 ? imageNameSplit[imageNameSplit.length-1] : "jpg"; //对存储路径进行处理 String imageLocation = realpath + "\\" + RandomUtil.generateGUID() + ".jpg" ; // 确定写出文件的位置 路径 + 文件md5摘要 + 文件类型 File file = new File(imageLocation); // 建立输出字节流 FileOutputStream fos = null; try { fos = new FileOutputStream(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); } // 用FileOutputStream 的write方法写入到文件中 try { fos.write(decode); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { // TODO e.printStackTrace(); } }
因为开发使用的是windows系统,所以系统的文件分隔符与linux的会不一致。
所以应该使用下列的方法。
        String separator = System.getProperty("file.separator");
        
        //将获取的base64字符串 转换成字节数组
        Base64 encoder = new Base64();
        byte[] decode = encoder.decode(imageBase64);
        //获取项目临时图片文件夹
        String realpath = ServletActionContext.getServletContext().getRealPath(separator+"tmp"+separator);
        //如果不存在则自行创建
        if (!new File(realpath).exists()) {
            new File(realpath).mkdir();
        }
        //以点号分割文件名   并截取文件类型名  如果不存在的话 则默认为jpg
//        String[] imageNameSplit = imageName.split("\\.");
//        String imageType = imageNameSplit.length > 1 ? imageNameSplit[imageNameSplit.length-1] : "jpg";
        
        //对存储路径进行处理
        String imageLocation = realpath + separator + RandomUtil.generateGUID() + ".jpg" ;
        
        // 确定写出文件的位置       路径  + 文件md5摘要 + 文件类型
        File file = new File(imageLocation);
        
        // 建立输出字节流
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        // 用FileOutputStream 的write方法写入到文件中
        try {
            fos.write(decode);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                // TODO 
                e.printStackTrace();
            }
        }
才能插入成功!
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号