Spring WebFlux FilePart transferTo method can't write file to dest path

Viewed 22
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.File;

@RestController
public class TestController {

    @PostMapping("test")
    public Mono<R> test(FilePart file){
        String fileName = file.filename();
        File newFile = new File("F:/images/banner/",fileName);
        file.transferTo(newFile);
        return Mono.just(R.ok());
    }
}

i upload picture and use transferTo method to write file to the dest path. but i can't found the picture in the F:/images/banner/ someone can help me? thanks

1 Answers

When writing reactive code you have to make sure it terminates, or in other words you need to subscribe to the publisher. The file.transferTo() returns a Mono<Void> which, if you don't subscribe, doesn't actually do anything.

What you can do in your case is the following, use the then method to return your result.

@PostMapping("test")
public Mono<R> test(FilePart file){
    String fileName = file.filename();
    File newFile = new File("F:/images/banner/",fileName);
    return file.transferTo(newFile)
      .then(Mono.just(R.ok()));
}

Now you return the call chain and the client will subscribe and things will start to happen. You could also add an additional onError call to return a error response when something breaks in the transfer.

Related