package org.ntlab.tampoposerver.utils;
import java.io.*;
import java.util.Base64;
public class Base64Decode {
//pathの位置にenImageをdecodeしたものを保存
private static void saveAsFile(String path, String enImage) throws IOException{
File file = new File(path); //pathの位置にfile作成準備
//enImageがnullならfile削除
if(enImage == null) {
file.delete();
return;
}
//enImage(文字列)をバイナリデータに変換
byte[] deData = Base64.getDecoder().decode(enImage);
// //親ディレクトリを作成し実際にfile作成
// file.getParentFile().mkdirs();
// file.createNewFile();
//
// //書き込み
// FileOutputStream fileOS = new FileOutputStream(file, false);
// BufferedOutputStream bf = new BufferedOutputStream(fileOS);
// bf.write(deData, 0, deData.length);
// bf.close();
// 親ディレクトリを作成(再帰的に)
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
// 上書きモードでファイル保存(存在しててもOK)
try (BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file, false))) {
bf.write(deData);
}
}
//{path1}/icon{id}.jpg に enImageをdecodeしたものを保存
public static String saveIcon(String id, String path1, String enImage) throws IOException {
String fileName = "icon" + id + System.currentTimeMillis() +".jpg";
String path = path1 + "/" + fileName;
saveAsFile(path, enImage);
return fileName;
}
}