[org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分 'file' 不存在

[org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present

我正在将 .pdf 文件上传到 mongo 数据库,我正在使用 GridFS 模板。

FileController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST, 
produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<?> 
 upload(@RequestParam("file")MultipartFile file) throws 
 IOException 
  {
    return new ResponseEntity<>(fileService.addFile(file), 
    HttpStatus.OK);
}

FileService.java

public String addFile(MultipartFile 上传)抛出 IOException {

    //define additional metadata
    DBObject metadata = new BasicDBObject();
    metadata.put("fileSize", upload.getSize());

    //store in database which returns the objectID
    Object fileID = template.store(upload.getInputStream(), upload.getOriginalFilename(), upload.getContentType(), metadata);

    //return as a string
    return fileID.toString();
}

编写控制器和服务方法后,出现此错误:

[org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]

谁能帮帮我,为什么我会收到这个异常?

谢谢

正如您提到的控制器中的服务器端 @RequestParam("file") MultipartFile file 因此您需要在从客户端上传文件时在表单数据中将密钥作为 file 传递。