Проблема с скачиванием файла
Добый день.
Я пишу демо приложении на Spring WebFlux + Thymeleaf.
Тут есть два метода:
- сохранить картину
- и потом скачать её.
Сохранине проходит успешно, но при попытке скачивания возникает ошибка и файл не может быть найден
Вот мой сервис
@Service
public class FileService {
private final String path = "./src/main/resources/upload/";
private final FileRepository fileRepository;
private final Path basePath = Paths.get("./src/main/resources/upload/");
ObjectMapper mapper = new ObjectMapper();
public FileService(FileRepository fileRepository) {
this.fileRepository = fileRepository;
}
public Mono<Void> upload(String name, Mono<FilePart> filePartMono){
return filePartMono
.flatMap(fp -> {
FileEntity items = mapper.convertValue(new FileEntity(fp.filename(), basePath + fp.filename()), FileEntity.class);
items.setName(name);
items.setPath(String.valueOf(basePath));
return fileRepository.save(items).then(Mono.just(fp));
})
.flatMap(fp -> fp.transferTo(basePath.resolve(fp.filename())))
.then();
}
public Mono<Void> download(String name, ServerHttpResponse response) throws FileNotFoundException {
String fileName = String.valueOf(getFileName(name));
ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName + "");
response.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);
File file = ResourceUtils.getFile(path + fileName);
return zeroCopyResponse.writeWith(file, 0, file.length());
}
Mono<FileEntity> getFileName(String name) throws RuntimeException {
return fileRepository.findByName(name);
}
}
Контроллер
private final FileService fileService;
public UploadController(FileService fileService) {
this.fileService = fileService;
}
@PostMapping(value = "file/single", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<Void> uploadV2(@RequestPart("user-name") String name ,@RequestPart("fileToUpload") Mono<FilePart> filePartMono) {
return fileService.upload(name , filePartMono);
}
@GetMapping("file/single")
public String uploadPage() {
return "upload";
}
@GetMapping("/download/file/one")
public Mono<Void> downloadFileOne(@RequestParam("token") String token,
ServerHttpResponse response ) throws IOException {
return fileService.download(token, response);
}
@GetMapping("/download/file")
public String dowloadFile() {
return "dowload";
}
Так же можете предложить какие нибудь варианты? Я новичок пока оссобо не шарю