首先,自己做下弯路总结,之前一直试,写入图片一直提示【图片错误】。后来网上查询方法,但是和自己写的都大同小异。但是为什么人家就不报错!此处,之前将data:image/png;base64,去掉,但还是报错,现在回想应该是后边编码问题。后来再将data:image/png;base64,去掉就显示了。
public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
byte[] buffer = null;
if(!PubMethod.isEmpty(base64Code)) {
buffer = new BASE64Decoder().decodeBuffer(base64Code);
}
if(!PubMethod.isEmpty(targetPath)) {
File file = new File(targetPath);
if(file.getParentFile()!=null && !file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
}
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
重要的:
String imgFile = request.getParameter("img").substring(request.getParameter("img").indexOf("base64,")+7);
上传成功!