前臺傳入base64格式圖片上傳,java後臺轉為MultipartFile
阿新 • • 發佈:2018-11-13
前臺傳入base64格式圖片上傳,java後臺轉為MultipartFile
之前一直用MultipartFile去接收檔案上傳的資料,但是今天接觸到app開發,前端from-data裡邊傳的是base64格式的值,在這裡做點小筆記,demo 以供參考:
程式設計師之間的交流做好的方式是程式碼:
|
|
:
public class BASE64DecodedMultipartFile implements MultipartFile { private final byte[] imgContent; private final String header; public BASE64DecodedMultipartFile(byte[] imgContent, String header) { this.imgContent = imgContent; this.header = header.split(";")[0]; } @Override public String getName() { return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; } @Override public String getOriginalFilename() { return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1]; } @Override public String getContentType() { return header.split(":")[1]; } @Override public boolean isEmpty() { return imgContent == null || imgContent.length ==0; } @Override public long getSize() { return imgContent.length; } @Override public byte[] getBytes() throws IOException { return imgContent; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File file) throws IOException, IllegalStateException { new FileOutputStream(file).write(imgContent); } }
因為之前都是用 MultipartFile 接收的值,所以在這裡需要實現一下MultipartFile的實現類,其中填的是自己的一些邏輯處理,
然後:
public class Base64StrToImage { Logger logger = LoggerFactory.getLogger(Base64StrToImage.class); public static MultipartFile base64MutipartFile(String imgStr){ try { String [] baseStr = imgStr.split(","); BASE64Decoder base64Decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = base64Decoder.decodeBuffer(baseStr[1]); for(int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b,baseStr[0]) ; }catch (Exception e){ e.printStackTrace(); return null; } } }
將接受到的base64格式值進行解碼;
這樣就可以直接使用了;
eg:
@RequestParam(required = false, value = "fileStr") String fileStr // 接收base64值(請求引數); try { Base64DecodedMultipartFile base64DecodedMultipartFile = null; if(null != fileStr && !fileStr.isEmpty()){ base64DecodedMultipartFile = (Base64DecodedMultipartFile) Base64StrToImage.base64MutipartFile(fileStr); } List<String> stringList = null; if (null !=base64DecodedMultipartFile && !base64DecodedMultipartFile.equals("")){ FileUploading fileUploading = new FileUploading(); stringList= fileUploading.phtoUpload(base64DecodedMultipartFile, request); } customerService.saveCustomer(customer, payments,stringList); //TODO 手機簡訊驗證碼,和第三方對接 return AjaxResult.successState("註冊成功", 0, ""); } catch (Exception ex) { return AjaxResult.error(ex.getMessage()); }
注:Base64DecodedMultipartFile : 定義的MultipartFile實現類;
FileUploading 檔案上傳工具類;request:這裡我需要它做檔案上傳的路徑;
測試:
C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.7985342453791074712.8080\upload/1537262907667.png
檔案儲存路徑:
這樣就可以簡單的實現檔案轉碼上傳了!!!!