Spring WebFlux: file transfer from the controller

Based on .NET and Node, it’s really hard for me to understand how to transfer this blocking MVC controller to the non-blocking annotated WebFlux controller? I understood the concepts, but could not find a suitable async Java IO method (which I would expect to return Flux or Mono).

@RestController
@RequestMapping("/files")
public class FileController {

    @GetMapping("/{fileName}")
    public void getFile(@PathVariable String fileName, HttpServletResponse response) {
        try {
            File file = new File(fileName);
            InputStream in = new java.io.FileInputStream(file);
            FileCopyUtils.copy(in, response.getOutputStream());
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
+4
source share
1 answer

First, a way to achieve this using Spring MVC should look like this:

@RestController
@RequestMapping("/files")
public class FileController {

    @GetMapping("/{fileName}")
    public Resource getFile(@PathVariable String fileName) {
        Resource resource = new FileSystemResource(fileName);        
        return resource;
    }
}

Also, not so, if you simply load these resources without additional logic, you can use Spring MVC static resource support . Using Spring Boot spring.resources.static-locationscan help you set up your location.

, Spring WebFlux, spring.resources.static-locations .

WebFlux . -, Mono<Resource> Resource, :

@RestController
@RequestMapping("/files")
public class FileController {

    @GetMapping("/{fileName}")
    public Mono<Resource> getFile(@PathVariable String fileName) {
        return fileRepository.findByName(fileName)
                 .map(name -> new FileSystemResource(name));
    }
}

, WebFlux, Resource , zero-copy, .

+1

Source: https://habr.com/ru/post/1694818/


All Articles