base64转为file文件
public JSONObject upload2(JSONObject json) {
File target = null;
InputStream ins;
BASE64DecodedMultipartFile base64DecodedMultipartFile = null;
if (null != json && null != json.get("file")) {
base64DecodedMultipartFile = (BASE64DecodedMultipartFile) Base64StrToImage.base64MutipartFile(json.get("file").toString().trim());
try {
ins = base64DecodedMultipartFile.getInputStream();
target = new File(base64DecodedMultipartFile.getOriginalFilename());
inputStreamToFile(ins, target);
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//调用上传接口
HttpResponse response = HttpRequest.post(uploadUrl).header("token", "NJhh2020").header("Content-Type", "multipart/form-data").form("mf", target).execute();
JSONObject result = JSONObject.parseObject(response.body());
return result;
}
base64编码进行解析两种写法,所有base64开头都是一样的data:image/jpg;base64
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;
}
}
public static MultipartFile base64ToMultipart(String base64) {
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(base64);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, "data:image/jpg;base64");
} catch (IOException e) {
e.printStackTrace();
return null;
}
}