java后台接受base64格式并转换为图片解决文件损坏问题

直接后台代码,因为接受的base64字符前面data:image/jpeg;base64,不是照片内容,去掉即可,否则会文件不识别(损坏)
/**
* 新增保存附件
*/
@PostMapping("/add")
@ResponseBody
public ResultBody addSave(HttpServletRequest request) throws IOException
{
ResultBody resultBody=new ResultBody();
//前台传过来的base64字符串
String r = request.getParameter(“base64img”)+"";
//去掉base64字符串的开头部分
String r3 = r.substring(r.indexOf(",")+1);
String filename = “”;
String filepath = “”;
//存储路径
filepath =“D:\profile\app\new1.jpg”;

    BASE64Decoder decoder = new BASE64Decoder();

//Base64解码
try{
byte[] b = decoder.decodeBuffer(r3);
for(int i=0;i {
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
java.io.OutputStream out = new java.io.FileOutputStream(filepath);
out.write(b);
out.flush();
out.close();
resultBody.setData(“success”);
}catch (IOException e){
e.printStackTrace();
resultBody.setData(“error”);
}
return resultBody;
}

你可能感兴趣的:(java后台接受base64格式并转换为图片解决文件损坏问题)