上传两个文件和一个对象失败并出现错误 415

Upload two files and an object are failing with error 415

我正在尝试使用一个 http rest 调用,该调用接受两个文件 a dto 的输入

@RequestMapping(name = "/my/endpoint", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE,
            MediaType.APPLICATION_JSON_VALUE})
    public @ResponseBody
    EndpointDto createEndpoint(@RequestBody MultipartFile requestFile, @RequestBody MultipartFile responseFile,
                               @RequestBody MyDto myDto){
        return endpointService.createEndpoint(requestFile, responseFile, myDto);
    }

我收到以下错误:

    org.springframework.web.HttpMediaTypeNotSupportedException: 
Content type 'multipart/form-data;boundary=----WebKitFormBoundarylq2UHYfBi0nAsRo7;charset=UTF-8' not supported

我通过 swagger 使用端点。 我认为问题出在我处理输入字段的方式上,但我不知道是什么问题。

您可以如下更改控制器参数

@RequestMapping(name = "/my/endpoint", method = RequestMethod.POST)
public ResponseEntity<EndpointDTO> createEndpoint(
   @RequestPart(value = "file1") MultipartFile filea, 
   @RequestPart(value = "file2") MultipartFile fileb, 
   @RequestPart MyDto myDto){
    return endpointService.createEndpoint(filea, fileb, myDto);
}

您可以使用 @RequestPart 获取文件和 DTO 值。

您可以使用以下 curl

在 API 以上进行测试
curl -v -H "Content-Type:multipart/form-data" -F "myDto=@body;type=application/json" -F "file1=@file1.txt" -F "file2=@file2.txt" -X POST http://<path>/my/endpoint

注意: 这里我使用 'body' 文件传递​​有效负载,使用 file1.txt & file2.txt 传递 MultipartFile。希望您熟悉curl命令并理解它。

示例控制器

@PostMapping(value = "/documents")
@Timed
public ResponseEntity<DocumentDTO> createDocument(@RequestPart String document, @RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest) throws URISyntaxException {

    DocumentDTO documentDTO = convertStringToDTO(document);

    DocumentDTO result = documentService.save(documentDTO, file);
    return ResponseEntity.created(new URI("/api/documents/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
        .body(result);
}

// com.fasterxml.jackson.databind.ObjectMapper;
private DocumentDTO convertStringToDTO(String document) {
    ObjectMapper objectMapper = new ObjectMapper();
    DocumentDTO documentDTO = null;
    try {
        documentDTO = objectMapper.readValue(document, DocumentDTO.class);
    } catch (IOException e) {
        log.error("DocumentString to JSON", e);
    }
    return documentDTO;
}

您必须从前端发送表单数据格式的数据,并将密钥作为包含字节和文档 JSON 对象的文件。