Questions raised:
I am working on a small website as a practice, but the front-end image is encrypted by base64 and is passed to the back-end for decoding. But there have always been problems, please give me advice
public static String base64ToImg(String src) throws IOException { String uuid = UUID.randomUUID().toString(); StringBuilder newPath = new StringBuilder(IMG_ROOT_PATH); newPath.append(separator). append(uuid). append(IMG_SUFFIX); if(src == null){ return null; } byte[] data = null; Base64.Decoder decoder = Base64.getDecoder(); try (OutputStream out = new FileOutputStream(newPath.toString())) { data = decoder.decode(src); out.write(data); return newPath.toString(); } catch (IOException e) { throw new IOException(); } }java.lang.IllegalArgumentException: Input byte array has wrong 4-byte ending unit
The above are related exception information. I'm trying to paste the base64 code of the front-end into notepad and then try to decode it myself, and the same problem is also true.
Solution:
IllegalArgumentException: Illegal parameter exception,
Try this, it should be OK.
Let me tell you the process:
Got stackoverflow, debug. Finally, I found that data is null. Come on, we need to learn a lot.
Next time I encounter a problem debug, see which code has a problem. By answering you, I have learned a lot.
The key point is here: throw new IOException();
try (OutputStream out = new FileOutputStream(newPath.toString())) { out.write(data); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("This is the exception thrown"); //throw new RuntimeException(e); } public static String base64ToImg(String src) throws IOException { String uuid = UUID.randomUUID().toString(); StringBuilder newPath = new StringBuilder("xx"); newPath.append("xx"). append(uuid). append("xx"); if (src == null) { return null; } byte[] data = Base64.getDecoder().decode(src); try (OutputStream out = new FileOutputStream(newPath.toString())) { out.write(data); } catch (IOException e) { e.printStackTrace(); } return newPath.toString(); }Add another commonly used shutdown resource:
public static String base64ToImg(String src) throws IOException { String uuid = UUID.randomUUID().toString(); StringBuilder newPath = new StringBuilder("xx"); newPath.append("xx"). append(uuid). append("xx"); if (src == null) { return null; } byte[] data = null; OutputStream out = null; Base64.Decoder decoder = Base64.getDecoder(); try { out = new FileOutputStream(newPath.toString()); data = decoder.decode(src); out.write(data); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } return newPath.toString(); }