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;
    }

你可能感兴趣的:(java,base64,File)