首页 > 解决方案 > 带有 ImageUpload 端点的空文件

问题描述

当我点击我的 imageupload 端点时,imageFile 将返回 null。我需要在某个地方设置一个集中配置来解析它吗?imageMetadata 通过就好了。

  @PostMapping(value = "/images/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String upload(
      @RequestPart(value = "imageFile", required = false) MultipartFile imageFile,
      @RequestPart(value = "imageMetadata", required = false) String imageMetadata
      ) {
    String imageFileIsNull = Boolean.toString(imageFile == null);
    return "Thanks for uploading your file! metadata:" + imageMetadata + " file is null: " + imageFileIsNull;
  }

附加照片时的返回值(我尝试过 jpg 和 png)

Thanks for uploading your file! metadata: hi file is null: true

标签: javaspringspring-bootrest

解决方案


尝试使用以下代码片段。

@PostMapping(value = "/images/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<ResponseMessage> upload(
      @RequestParam("file") MultipartFile imageFile
      ) {

    String imageFileIsNull = Boolean.toString(imageFile == null);
    String message = "Thanks for uploading your file! " + " file is null: " + imageFileIsNull;
    return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
  }

我删除了用于测试的图像元数据,以便您可以确保代码正常工作。


推荐阅读