小编典典

带有JSON的Spring MVC多部分请求

spring

我想使用Spring MVC发布带有一些JSON数据的文件。因此,我开发了一项休息服务

@RequestMapping(value = "/servicegenerator/wsdl", method = RequestMethod.POST,consumes = { "multipart/mixed", "multipart/form-data" })
@ResponseBody
public String generateWSDLService(@RequestPart("meta-data") WSDLInfo wsdlInfo,@RequestPart("file") MultipartFile file) throws WSDLException, IOException,
        JAXBException, ParserConfigurationException, SAXException, TransformerException {
    return handleWSDL(wsdlInfo,file);
}

当我从其他客户端发送请求时 content-Type = multipart/form-data or multipart/mixed,出现下一个异常: org.springframework.web.multipart.support.MissingServletRequestPartException

谁能帮助我解决这个问题?

我可以@RequestPart同时将Multipart和JSON发送到服务器吗?


阅读 592

收藏
2020-04-11

共1个答案

小编典典

这就是我使用JSON数据实现Spring MVC Multipart Request的方式。

带有JSON数据的分段请求(也称为混合分段):

基于Spring 4.0.2版本中的RESTful服务,可以使用@RequestPart来实现HTTP请求,其中第一部分为XML或JSON格式的数据,第二部分为文件。以下是示例实现。

Java代码段:

Controller中的Rest服务将混合使用@RequestPart和MultipartFile来满足此类Multipart + JSON请求。

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

前端(JavaScript)代码段:

  1. 创建一个FormData对象。

  2. 使用以下步骤之一将文件追加到FormData对象。

  3. 如果文件已使用“文件”类型的输入元素上载,则将其附加到FormData对象。 formData.append("file", document.forms[formName].file.files[0]);

  4. 将文件直接附加到FormData对象。 formData.append("file", myFile, "myfile.txt");要么formData.append("file", myBob, "myfile.txt");
  5. 创建带有字符串化JSON数据的Blob,并将其附加到FormData对象。这将导致multipart请求中第二部分的Content-type“ application / json”,而不是文件类型。

  6. 将请求发送到服务器。

  7. 要求详细信息:
    Content-Type: undefined。这将导致浏览器将Content-Type设置为multipart / form-data并正确填充边界。手动将Content-Type设置为multipart / form-data将无法填写请求的边界参数。

JavaScript代码:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

要求详细信息:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

请求有效负载:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--
2020-04-11