1、编码
以文件上传为例,把文件转成base64。
@PostMapping("base64")
public String base64(MultipartFile file) throws IOException {
return Base64.getEncoder().encodeToString(file.getBytes());
}
2、解码
前端传base64和文件名称(也可以改成文件类型,名称用UUID或者其它,这里就不展示了)。如:xxx.jpg/xxx.txt/xxx.word等。
@PostMapping("upload")
public void upload(String fileBase64, String fileName) throws IOException {
//filePath为D:/1.txt
String filePath = System.getProperty("user.dir") + "/" + fileName;
// System.out.println(filePath);
Files.write(Paths.get(filePath), Base64.getDecoder().decode(fileBase64), StandardOpenOption.CREATE);
}