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) {// 調(diào)整異常數(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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
如何解決Spring的UnsatisfiedDependencyException異常問題
這篇文章主要介紹了如何解決Spring的UnsatisfiedDependencyException異常問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
使用lombok的@Data會導致棧溢出StackOverflowError問題
這篇文章主要介紹了使用lombok的@Data會導致棧溢出StackOverflowError問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
Spring Security在標準登錄表單中添加一個額外的字段
這篇文章主要介紹了Spring Security在標準登錄表單中添加一個額外的字段,我們將重點關注兩種不同的方法,以展示框架的多功能性以及我們可以使用它的靈活方式。 需要的朋友可以參考下2019-05-05
Mybatis-plus如何提前獲取實體類用雪花算法生成的ID
本文主要介紹了Mybatis-plus如何提前獲取實體類用雪花算法生成的ID,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07

