Попытка отправить Http-ответ интерфейсу до того, как произойдет логика метода

#spring-boot #spring-mvc #asynchronous #file-upload

#весенняя загрузка #spring-mvc #асинхронный #загрузка файла

Вопрос:

Чего я пытаюсь достичь, так это того, что у меня есть контроллер, доступ к которому осуществляется из интерфейса (Angular). Пользователи загружают массив изображений из интерфейса, и эти изображения отправляются и обрабатываются через серверную часть (Spring Boot). Перед обработкой изображений я хотел бы отправить ответ (200) интерфейсу, чтобы пользователю не приходилось ждать обработки изображений. Код выглядит так:

 @CrossOrigin
@RestController
public class SolarController {

    @Autowired
    SolarImageServiceImpl solarImageService;

    @Autowired
    SolarVideoServiceImpl solarVideoService;

    @ApiOperation(value = "Submit images")
    @PostMapping(value="/solarImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void getUploadImages(@ApiParam(value = "Upload images", required = true) @RequestPart(value = "files") MultipartFile[] files,
                                             @ApiParam(value = "User's LanId", required = true) @RequestParam(value = "lanID") String lanId,
                                             @ApiParam(value = "Site name", required = true) @RequestParam(value = "siteName") String siteName,
                                             @ApiParam(value = "User email", required = true) @RequestParam(value = "userEmail") String userEmail,
                                             @ApiParam(value = "Inspection ID", required = true) @RequestParam(value = "inspectionID") String inspectionID) throws IOException{

        if (!ArrayUtils.isEmpty(files)) {
            this.solarImageService.uploadImages(files, lanId, siteName, userEmail, inspectionID);
        }
  

Я рассмотрел множество других примеров, например, при использовании @Async поверх метода, использовании HttpServletResponse и настройке собственных ответов. Но ничего не работает.

Ответ №1:

Решено.

 @ApiOperation(value = "Submit images")
    @PostMapping(value="/solarImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void getUploadImages(@ApiParam(value = "Upload images", required = true) @RequestPart(value = "files") MultipartFile[] files,
                                             @ApiParam(value = "User's LanId", required = true) @RequestParam(value = "lanID") String lanId,
                                             @ApiParam(value = "Site name", required = true) @RequestParam(value = "siteName") String siteName,
                                             @ApiParam(value = "User email", required = true) @RequestParam(value = "userEmail") String userEmail,
                                             @ApiParam(value = "Inspection ID", required = true) @RequestParam(value = "inspectionID") String inspectionID, HttpServletResponse response) throws IOException{

int code = (!ArrayUtils.isEmpty(files)) ? HttpServletResponse.SC_OK
                : HttpServletResponse.SC_NOT_FOUND;
        if (code != HttpServletResponse.SC_OK) {
            response.sendError(code);
            return;
        }

        PrintWriter wr = response.getWriter();
        response.setStatus(code);
        wr.flush();
        wr.close();

        if (!ArrayUtils.isEmpty(files)) {
            this.solarImageService.uploadImages(files, lanId, siteName, userEmail, inspectionID);
        }
  

Сначала отправка HttpServletResponse сделала свое дело. Аннотирование метода с помощью @Async не сработало.