I am a student who has just started to learn Spring boot and java.
I am implementing code that insert information about multipart file list into a one-to-many table as POST.
like this.
For one-to-many relationships, I refer to the tutorial posting below.
https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/
Like the tutorial, I want to use @RequestBody
, but using multipartFile
and @RequestBody
results in an error so I am using @RequestParam
.
But it doesn't work normally because of my lack of Java basic knowledge.
What I want to do is to bring the epi_storage's id by findById
and then save the information of file list with @RequestParam MultipartFile
to the sub_storage table.
below is controller.
@PostMapping (value ="/newSub", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public SubStorage NewSub(@PathVariable (value="epiId") int epiId,
@RequestParam("subFiles") MultipartFile[] subFiles) {
return subStorageDAO.findById(epiId).map( -> {
return Arrays.asList(subFiles)
.stream()
.map(subFile->uploadFile(subFile))
.collect(Collectors.toList());
}).orElseThrow(() -> new ResourceNotFoundException("EpiId " + epiId + " not found"));
}
public SubStorage uploadFile(@RequestParam("subFile") MultipartFile subFile) {
SubStorage subStorage = subStorageService.storeSubFile(epiId, subFile);
return subStorage;
}
below is service's storeSubFile()
public SubStorage storeSubFile(int epiId, MultipartFile subFile) {
EpiStorage epiStorage = SubStorage.setEpiStorage(epiId);
// Normalize file name
String subFileName = StringUtils.cleanPath(subFile.getOriginalFilename());
String subFileUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/uploads/")
.path(subFileName)
.toUriString();
try {
if(subFileName.contains("..")) {
throw new FileStorageException ("There is a wrong word in " + subFileName);
}
//Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(subFileName);
Files.copy(subFile.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
SubStorage subStorage = new SubStorage(subFileName, subFileUri, subFile.getContentType(), subFile.getSize(), epiStorage);
subStorageDAO.save(subStorage);
return subStorage;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " +subFileName + ". Please try again!", ex);
}
}
sorry for my bad code...
Maybe I'm a lot wrong with Java grammar. But I don't know where to fix it.
I'd really appreciate for your help.