java实现Base64位编码转附件

java实现Base64位编码转附件

工作中用到的,记录下来,下次使用好借鉴。

上代码(web-info路径下面,类名及导包同下)

//拿到带有base64编码的json并解析拿到纯base64编码
	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());
        }
    }
	
	
}

借鉴于:

https://www.cnblogs.com/lovling/p/6666994.html?utm_source=itdadao&utm_medium=referral

https://blog.csdn.net/shaohe18362202126/article/details/80717385

如有侵权,请联系删除!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值