JavaUtil 处理Base64的图片上传
UploadImageBase64.java
package com.lee.util; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import sun.misc.BASE64Decoder; public class UploadImageBase64 { static String basePath = System.getProperty("searchData"); public static String uploadImage(String imageFile) { // 通过base64来转化图片 imageFile = imageFile.replaceAll("data:image/jpeg;base64,", ""); BASE64Decoder decoder = new BASE64Decoder(); // Base64解码 byte[] imageByte = null; try { imageByte = decoder.decodeBuffer(imageFile); for (int i = 0; i < imageByte.length; ++i) { if (imageByte[i] < 0) {// 调整异常数据 imageByte[i] += 256; } } } catch (Exception e) { e.printStackTrace(); } // 生成文件名 String files = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000) + ".png"; // 生成文件路径 String filename = basePath + "assets\\images\\" + files; // System.out.println(filename); try { // 生成文件 File newimageFile = new File(filename); newimageFile.createNewFile(); if (!newimageFile.exists()) { newimageFile.createNewFile(); } OutputStream imageStream = new FileOutputStream(newimageFile); imageStream.write(imageByte); imageStream.flush(); imageStream.close(); } catch (Exception e) { e.printStackTrace(); } return files; } }