首页 > 解决方案 > 尝试在方法逻辑发生之前向前端发送 Http 响应

问题描述

我想要完成的是我有一个可以从前端(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 以及设置我自己的响应。但没有任何工作。

标签: spring-bootspring-mvcasynchronousfile-upload

解决方案


解决。

@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 注释该方法不起作用。


推荐阅读