Multipartfile stored empty in session?

17 Views Asked by At

I am trying to upload a file via a spring rest endpoint, store the file in an Object using the "@SessionScope" annotation and then retrieve the data in a second request.

My problem: The file uploads without any problems and the server returns the status code 200. If i try to retrieve the filedata in the second request the file is empty. This is weird since the file that I uploaded before isn't empty. The really strange part is that the fileName matches so it didn't create a new session.

My code:

controller

@RestController
@RequestMapping("/file")
public class FileUploadController {
    private final SessionFile sessionFile;

    public FileUploadController(SessionFile sessionFile) {
        this.sessionFile = sessionFile;
    }

    @GetMapping
    public FileDto getFileDataFromSession() {
        return FileDto.of(sessionFile.getFile());
    }
    @PostMapping
    public void uploadFile(@RequestParam("file") MultipartFile file) {
        sessionFile.setFile(file);
    }
}

sessionFile

@Component
@SessionScope
@Getter
@Setter
public class SessionFile {
    private MultipartFile file;
}

fileDto (for response in the second request)

@Getter
@Setter
public class FileDto {
    private String fileName;
    private Long fileSize;
    private String fileType;

    public static FileDto of(MultipartFile file) {
        FileDto fileDto = new FileDto();
        fileDto.fileName = file.getOriginalFilename();
        fileDto.fileSize = file.getSize();
        fileDto.fileType = file.getContentType();

        return fileDto;
    }
}

If i add System.out.println("out: " + sessionFile.getFile().getSize()); to the second endpoint (the one to receive the data) and System.out.println("in: " + sessionFile.getFile().getSize()); to the upload endpoint i get the following logged to my console:

in: 151951
out: 0

I already tried different annotations @Scope("session") and @SessionScope. I also tried to use the Java.io.File Class instead of the Multipartfile class but with no success. The file seems doesn't want to be stored!

0

There are 0 best solutions below