java實現(xiàn)后臺處理base64圖片還原為文件
后臺處理base64圖片還原為文件
/**
* 將base64圖片解析成文件存放本地
* @param imgStr
* @return 本地臨時文件的地址
*/
private static String generateImage(String imgStr){
if(Strings.isNullOrEmpty(imgStr)){
return null;
}
BASE64Decoder decoder = new BASE64Decoder();
//轉換前端數(shù)據(jù)
imgStr = imgStr.replaceAll(" ", "+");
//去除多余部分
imgStr=imgStr.replace("data:image/png;base64,", "");
try {
// Base64解碼
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; i++) {
if (b[i] < 0) {// 調整異常數(shù)據(jù)
b[i] += 256;
}
}
String filepath =System.getProperty("java.io.tmpdir") +"測試"+System.currentTimeMillis()+".png";
File file = new File(filepath);
if(file.exists()){
file.delete();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(b);
fos.flush();
fos.close();
logger.info("路徑"+filepath);
return filepath;
}catch(Exception e){
return null;
}
}
//imgStr=imgStr.replace(“data:image/png;base64,”, “”); 關鍵地方 根據(jù)圖片類型 過濾對應的類型
java Base64解析
最近在業(yè)務場景中,需要對第三方傳遞進來的字符進行base64解密,根據(jù)第三方文檔提供的解析工具,對數(shù)據(jù)進行了解析
關于Base64的解析方式如下
?String sign = "xxxxxxxxxxxxxxxxxxxxxxxx"; ?sun.misc.BASE64Decoder decode = new sun.misc.BASE64Decoder(); ?String json = new String(decode.decodeBuffer(sign));
使用sun.misc.BASE64Decoder對數(shù)據(jù)解析,放測試環(huán)境測試發(fā)現(xiàn)解析出來的字符串正確無誤,
但是在上線之后,根據(jù)第三方傳遞的sign,解析出來之后發(fā)現(xiàn)字符串最后多了一個字符 “7”,查詢邏輯 沒有發(fā)現(xiàn)問題,最后猜測是sun.misc.BASE64Decoder出了問題,于是換了Base64的解析jira
使用如下代碼解析
String sign = "xxxxxxxxxxxxxxxxxxxxxxxxx"; Base64 base64 = new Base64(); String json = new String (base64.decodeBase64(sign.getBytes()));
發(fā)現(xiàn)返回json中數(shù)據(jù)正常,問題解決。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java concurrency線程池之線程池原理(一)_動力節(jié)點Java學院整理
這篇文章主要為大家詳細介紹了Java concurrency線程池之線程池原理,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
有關ServletConfig與ServletContext的訪問
下面小編就為大家?guī)硪黄嘘PServletConfig與ServletContext的訪問。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01

