2 Star 6 Fork 5

AmCoder / AmCoder

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
实现从json中提取Base64编码并转附件.md 6.04 KB
一键复制 编辑 原始数据 按行查看 历史

!> commit by jzh

  • 从带有base64的json中获取base64,并且获取json中提供的附件名和格式
public static void getBase64(String str) throws IOException{
	String aaString = null;
	try {
		//获取当前文件的绝对路径
		aaString = CreateNewFileUtil.class.getClassLoader().getResource("").toURI().getPath();
	} catch (URISyntaxException e) {
		e.printStackTrace();
	}
	String base64 = null;
	String fileFormat = null;
	if (StringUtils.hasText(str)) {
		//传入的str是json格式的字符串,进行分隔解析。
		JSONObject json_test = JSONObject.fromObject(str);
		//得到json中data里面的字符串,并转为json格式
		String baseJson = json_test.get("data").toString().replace("[", "").replace("]", "");
		JSONObject json_test2 = JSONObject.fromObject(baseJson);
		//拿到base64位编码
		base64 = json_test2.get("file_path")+"";
		//拿到要转化的附件的名称及格式
		fileFormat = json_test2.get("file_name")+"";
	}
	//根据获取的绝对路径定位到web-info下的位置,进行创建文件
	String path = aaString.substring(1,aaString.length()-8)+fileFormat;
	//文件的完整名称,如spring.jpeg
      String filename = fileFormat;
      //文件名,如spring
      String name = filename.substring(0,filename.indexOf("."));
      //文件后缀,如.jpeg
      String suffix = filename.substring(filename.lastIndexOf("."));
      //目标文件
      File descFile = new File(path);
      int i = 1;
      //若文件存在重命名
      while(descFile.exists()) {
          String newFilename = name+"("+i+")"+suffix;
          path = aaString.substring(1,aaString.length()-8)+newFilename;
          //目标文件
          descFile = new File(path);
          if (!descFile.exists()) {
			continue;
		}
          i++;
      }
	base64ToFile(base64,path);
}
  • 将base64转为file
public static boolean base64ToFile(String base64,String path) {
    byte[] buffer;
    try {
    	//用公司封装的base64Util进行解码。
        buffer = Base64.decode(base64);
        //用BASE64Decoder实现(建议使用本方法)。
        buffer = new BASE64Decoder().decodeBuffer(base64);
        //放入要输出文件的地址
        FileOutputStream out = new FileOutputStream(path);
        out.write(buffer);
        out.close();
        return true;
    } catch (Exception e) {
        throw new RuntimeException("base64字符串异常或地址异常\n" + e.getMessage());
    }
}
  • 整体代码如下

通过.properties配置文件动态配置生成的文件路径(又增加了文件夹不存在自动创建的功能)

package com.risen.sjcj.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import net.sf.json.JSONObject;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

public class CreateNewFileUtil {

	private String fileUrl;

	public CreateNewFileUtil() {
		//读取文件路径的配置文件
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/risen/base/config/fileUrl.properties");
		Properties p =new Properties();
		try {
			p.load(inputStream);
			this.fileUrl=p.getProperty("dataSource.fileUrl");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	//拿到带有base64编码的json并解析拿到纯base64编码
	public static void getBase64(String str) throws IOException{

		CreateNewFileUtil createNewFileUtil = new CreateNewFileUtil();
		String url = null;
		//获取文件路径的配置信息
		url = createNewFileUtil.fileUrl;
		String base64 = null;
		String fileFormat = null;
		if (StringUtils.hasText(str)) {
			//传入的str是json格式的字符串,进行分隔解析。
			JSONObject json_test = JSONObject.fromObject(str);
			//得到json中data里面的字符串,并转为json格式
			String baseJson = json_test.get("data").toString().replace("[", "").replace("]", "");
			JSONObject json_test2 = JSONObject.fromObject(baseJson);
			//拿到base64位编码
			base64 = json_test2.get("file_path")+"";
			//拿到要转化的附件的名称及格式
			fileFormat = json_test2.get("file_name")+"";
		}
		//根据获取的绝对路径定位到web-info下的位置,进行创建文件
		String path = url+fileFormat;
		//文件的完整名称,如spring.jpeg
        String filename = fileFormat;
        //文件名,如spring
        String name = filename.substring(0,filename.indexOf("."));
        //文件后缀,如.jpeg
        String suffix = filename.substring(filename.lastIndexOf("."));
        //目标文件
        File descFile = new File(path);
        //获取文件上一级文件夹地址
        File fileParent = descFile.getParentFile();
        //判断该文件夹存在不存在,不存在自动创建
        if(!fileParent.exists()){
            fileParent.mkdirs();
        }
        int i = 1;
        //若文件存在重命名
        while(descFile.exists()) {
            String newFilename = name+"("+i+")"+suffix;
            //path = url.substring(1,url.length()-8)+newFilename;
            path = url+newFilename;
            //目标文件
            descFile = new File(path);
            if (!descFile.exists()) {
				continue;
			}
            i++;
        }
		base64ToFile(base64,path);
	}
	 // 将 base64 转化为 file
    public static boolean base64ToFile(String base64,String path) {

        byte[] buffer;
        try {
        	//用公司封装的base64Util进行解码。
            buffer = Base64.decode(base64);
            //用BASE64Decoder实现(建议使用本方法)。
            buffer = new BASE64Decoder().decodeBuffer(base64);
            //放入要输出文件的地址
            FileOutputStream out = new FileOutputStream(path);
            out.write(buffer);
            out.close();
            return true;
        } catch (Exception e) {
            throw new RuntimeException("base64字符串异常或地址异常\n" + e.getMessage());
        }
    }
}
其他
1
https://gitee.com/AmCoder/AmCoder.git
git@gitee.com:AmCoder/AmCoder.git
AmCoder
AmCoder
AmCoder
master

搜索帮助