java把base64位编码转为File文件并存到本地

public File getFileFromBase64(String base) throws Exception {
        String base64Pic = base;
        File file = null;
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (base64Pic == null) { // 图像数据为空
            resultMap.put("resultCode", 0);
            resultMap.put("msg", "图片为空");
        } else {
            BASE64Decoder decoder = new BASE64Decoder();
            String baseValue = base64Pic.replaceAll(" ", "+");//前台在用Ajax传base64值的时候会把base64中的+换成空格,所以需要替换回来。
            byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));//去除base64中无用的部分
            base64Pic = base64Pic.replace("base64,", "");
            SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
            String nowDate = df2.format(new Date());
            String imgFilePath = QMConfig.filePathRoot + "\\" + nowDate + "\\" + System.currentTimeMillis();
            File file1 = new File(imgFilePath);
            if (!file1.exists() && !file1.isDirectory()) {//判断文件路径下的文件夹是否存在,不存在则创建
                file1.mkdirs();
            }
            try {
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 调整异常数据
                        b[i] += 256;
                    }
                }
                file = new File(imgFilePath + "\\" + System.currentTimeMillis());
                // 如果要返回file文件这边return就可以了,存到临时文件中
                OutputStream out = new FileOutputStream(file.getPath());
                out.write(b);
                out.flush();
                out.close();
            } catch (Exception e) {
                resultMap.put("resultCode", 0);
                resultMap.put("msg", "存储异常");
            }

        }
        return file;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值