base64转为file文件

本文介绍了如何将Base64编码的图片数据转换为File对象,并通过上传接口实现文件上传,同时展示了两种常用的Base64解码方法。重点在于实际应用中处理Base64编码数据到文件操作的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

base64转为file文件

public JSONObject upload2(JSONObject json) {
		File target = null;
		InputStream ins;
		BASE64DecodedMultipartFile base64DecodedMultipartFile = null;
		if (null != json && null != json.get("file")) {
			base64DecodedMultipartFile = (BASE64DecodedMultipartFile) Base64StrToImage.base64MutipartFile(json.get("file").toString().trim());
			try {
				ins = base64DecodedMultipartFile.getInputStream();
				target = new File(base64DecodedMultipartFile.getOriginalFilename());
				inputStreamToFile(ins, target);
				ins.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		//调用上传接口
		HttpResponse response = HttpRequest.post(uploadUrl).header("token", "NJhh2020").header("Content-Type", "multipart/form-data").form("mf", target).execute();
		JSONObject result = JSONObject.parseObject(response.body());
		return result;
	}

base64编码进行解析两种写法,所有base64开头都是一样的data:image/jpg;base64

public static MultipartFile base64MutipartFile(String imgStr) {
        try {
            String[] baseStr = imgStr.split(",");
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = base64Decoder.decodeBuffer(baseStr[1]);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, baseStr[0]);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
public static MultipartFile base64ToMultipart(String base64) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, "data:image/jpg;base64");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值