Spring File Upload
Let's create a simple file upload control and service.
Source
Controller
This is the controller part.
It simply receives a form object and returns a boolean.
// File Upload
@PostMapping("/file")
public boolean fileUpload(@RequestBody MultipartFile[] files) {
return fileService.upload(files);
}
Service
This is the service part where the file is actually saved.
I've summarized it as briefly as possible.
// Upload
public boolean upload(MultipartFile[] files) {
private String filePath = "C:/tmp/file";
for (MultipartFile file: files) {
// Get the file name
String orginalName = file.getOriginalFilename();
assert orginalName != null;
String fileName = orginalName.substring(orginalName.lastIndexOf("\\") + 1);
// Create a folder
File uploadPathFolder = new File(path);
if(!uploadPathFolder.exists()) {
uploadPathFolder.mkdirs();
}
// Create a unique ID
UUID uuid = UUID.randomUUID();
// Specify the file path to be saved
String saveFileName String.format("%s__%s", uuid.toString(), FileName);
String orgPathFile = String.format("%s%s%s", filePath, File.separator, saveFileName);
Path savePath = Paths.get(orgPathFile);
try {
file.transferTo(savePath); // actual save
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
Example
Other examples
Spring server-side upload
Spring server-side download
Client JavaScript Fetch upload
Client JavaScript Fetch download