spring-boot - 尝试在方法逻辑发生之前向前端发送 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 以及设置我自己的响应。但没有任何工作。
解决方案
解决。
@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 注释该方法不起作用。
推荐阅读
- php - 使用 Laravel Artisan [Laravel 8] 创建我的自定义类
- javascript - 使用 JSX 时如何让 Tree Shaking 在 Vuetify 中工作?
- optaplanner - optaplanner 使用动态配置的时间提供的最佳解决方案
- java - HttpClients.createSystem() 与 HttpClients.createDefault() 之间的区别?
- tinymce - TinyMCE 仅允许来自白名单域的图像或仅允许上传
- python - RobertaForSequenceClassification 中的 logits 和概率代表什么?
- python - 密码重置视图显示 django 框架模板
- ruby-on-rails - 更改自定义配置文件时运行自定义代码块,类似于 Rails I18n 重新加载的工作原理?
- java - 整数数组的 Java 流以返回对象列表
- c - C 共享对象库生成文件