springboot2接收前端傳的base64格式圖片資料,轉成圖片
阿新 • • 發佈:2019-01-12
參考:https://blog.csdn.net/zmx729618/article/details/78038764 @PostMapping("/base64Upload") public AppResult<String> uploadImage(String base64Data){ log.info("==上傳圖片=="); log.info("==接收到的資料=="+base64Data); String dataPrix = ""; //base64格式前頭 String data = "";//實體部分資料 if(base64Data==null||"".equals(base64Data)){ return AppResultBuilder.buildFailedResult("上傳失敗,上傳圖片資料為空","401"); }else { String [] d = base64Data.split("base64,");//將字串分成陣列 if(d != null && d.length == 2){ dataPrix = d[0]; data = d[1]; }else { return AppResultBuilder.buildFailedResult("上傳失敗,資料不合法","401"); } } 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 AppResultBuilder.buildFailedResult("上傳圖片格式不合法","401"); } String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String tempFileName=uuid+suffix; String imgFilePath = "G:\\Images\\"+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(); String imgurl="http://xxxxxxxx/"+tempFileName; //imageService.save(imgurl); return AppResultBuilder.buildSuccessResult(imgurl,"200"); } catch (IOException e) { e.printStackTrace(); return AppResultBuilder.buildFailedResult("上傳圖片失敗","401"); } }