前端傳遞了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 "上傳圖片失敗"; } } }