Сохранение MultipartFile в определенном месте из контроллера в Java
У меня есть веб-приложение, в котором пользователь загружает файл в свою папку, которая создается, когда пользователь создает учетную запись, но у меня возникают проблемы с указанием правильного пути для сохранения файла:(
@PostMapping("/uploadFile")
public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
String getNameUntilCharAt = SecurityContextHolder.getContext().getAuthentication().getName().toString().split("\\@")[0];
Path storageLocation = Paths.get("./uploads", getNameUntilCharAt+"/");
String fileName = fileStorageService.storeFile(file,storageLocation);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
return new UploadFileResponse(fileName, fileDownloadUri,
file.getContentType(), file.getSize());
}
Вот метод, который хранит файлы
public String storeFile(MultipartFile file, Path targetLocation) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if(fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
/*Path targetLocation = this.fileStorageLocation.resolve(fileName);*/
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
В основном эти две строки важны:
Path storageLocation = Paths.get("./uploads", getNameUntilCharAt+"/");
String fileName = fileStorageService.storeFile(file,storageLocation);
Я получаю путь и передаю его методу, который хранит файл, но путь, который я указываю, всегда неверен. Например, если getNameUntilCharAt является тестовым, он не сохранит файл в./uploads/getNameUntilCharAt/nameOfThe файл. Он перезапишет имя папки и в основном сохранит файл с именем getNameUntilCharAt, что странно. Я не очень понимаю, почему он перезаписывает имя папки