前端传递了Base64编码的文件后,将文件保存进本地或者服务器,并将文件的名称进行重新命名的工具类
package com.xz.util; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import java.io.*; import java.util.UUID; /** * 对上传的图片进行操作 * * @author zagwk * @version 1.0 * @date 2020/7/4 13:44 */ public class PhotoUtil { /** * MultipartFile类型的文件 * @param imgFile * @return * @throws IOException */ public String memoryPhoto(MultipartFile imgFile) throws IOException { String originalFilename = imgFile.getOriginalFilename();//获取原始文件名 if (originalFilename != null && !originalFilename.equals("")) { int index = originalFilename.lastIndexOf(".");//找到 . 的位置 String suffix = originalFilename.substring(index);//根据 . 的位置进行分割,拿到文件后缀名 String fileName = UUID.randomUUID().toString() + suffix;//uuid生成新的文件名 //将图片保存到本地 File file = new File("E:\img"); if (!file.exists()) { file.mkdirs(); } String path = "E:\img/" + fileName; //实现上传 imgFile.transferTo(new File(path)); return fileName; } return null; } /** * Base64编码格式 * @return * @throws IOException */ public String GenerateImage(String base64Data) throws IOException { String dataPrix = ""; //base64格式前头 String data = "";//实体部分数据 if (base64Data == null || "".equals(base64Data)) { return "上传失败,上传图片数据为空"; } else { String[] d = base64Data.split("base64,");//将字符串分成数组 if (d != null && d.length == 2) { dataPrix = d[0]; data = d[1]; } else { return "上传失败,数据不合法"; } } String suffix = "";//图片后缀,用以识别哪种格式数据 //data:image/jpeg;base64,base64编码的jpeg图片数据 if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) { suffix = ".jpg"; } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) { //data:image/x-icon;base64,base64编码的icon图片数据 suffix = ".ico"; } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) { //data:image/gif;base64,base64编码的gif图片数据 suffix = ".gif"; } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) { //data:image/png;base64,base64编码的png图片数据 suffix = ".png"; } else { return "上传图片格式不合法"; } String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String tempFileName = uuid + suffix; String imgFilePath = "E:\img\" + tempFileName;//新生成的图片 BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解码 byte[] b = decoder.decodeBuffer(data); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { //调整异常数据 b[i] += 256; } } OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); //imageService.save(imgurl); return tempFileName; } catch (IOException e) { e.printStackTrace(); return "上传图片失败"; } } }