@RequestPart混合多部分请求,春季MVC 3.2(@RequestPart with mi

2019-09-01 04:58发布

我正在开发基于Spring 3.2 RESTful服务。 我现在面临的问题与控制器处理混合多部分的HTTP请求,与XMLor JSON格式的数据,而第二部分与图像文件的第二部分。

我使用@RequestPart注释用于接收请求

@RequestMapping(value = "/User/Image", method = RequestMethod.POST,  consumes = {"multipart/mixed"},produces="applcation/json")

public
ResponseEntity<List<Map<String, String>>> createUser(
        @RequestPart("file") MultipartFile file, @RequestPart(required=false) User user) {

    System.out.println("file" + file);

    System.out.println("user " + user);

    System.out.println("received file with original filename: "
            + file.getOriginalFilename());

    // List<MultipartFile> files = uploadForm.getFiles();
    List<Map<String, String>> response = new ArrayList<Map<String, String>>();
    Map<String, String> responseMap = new HashMap<String, String>();

    List<String> fileNames = new ArrayList<String>();

    if (null != file) {
        // for (MultipartFile multipartFile : files) {

        String fileName = file.getOriginalFilename();
        fileNames.add(fileName);

        try {
            file.transferTo(new File("C:/" + file.getOriginalFilename()));
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    responseMap.put("displayText", file.getOriginalFilename());
    responseMap.put("fileSize", "" + file.getSize());
    response.add(responseMap);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Accept", "application/json");
    return new ResponseEntity<List<Map<String, String>>>(response,
            httpHeaders, HttpStatus.OK);

}

User.java会像这个 -

@XmlRootElement(name = "User")


public class User implements Serializable { 
    private static final long serialVersionUID = 1L;

    private int userId;
    private String name;
    private String email;

    private String company;
    private String gender;

    //getter setter of the data members
}

据我了解,使用@RequestPart注解我希望这取决于其Content-Type和最后未整理到我的用户类别进行评估的XML多段(我用JAXB2,编组/ unmarhaller正确的配置当我通过XML数据作为主体,并使用@RequestBody注解)应用程序上下文和程序工作正常所有其他控制器的方法。

但是,什么是实际发生的是,虽然该文件被正确地发现和解析为MultipartFile,“用户”的一部分是从未见过的,并请求总是失败,不匹配的控制器方法签名。

我再现了问题,几个客户类型,我相信多部分请求的格式就可以了。

请帮我解决这个问题,也许一些解决办法将在那里接受混合/多请求。

感谢致敬,

Hriagvendra

Answer 1:

不知道你是否有固定的问题,但我也有我的地方JSON对象没有得到我的控制器混合@RequestPart和MultipartFile在一起时拿起一个类似的问题。

你的电话的方法签名看起来是正确的:

public ResponseEntity<List<Map<String, String>>> createUser(
        @RequestPart("file") MultipartFile file, @RequestPart(required=false) User user) {

// ... CODE ... 
}

但是要确保你的要求看起来是这样的:

POST /createUser
Content-Type: multipart/mixed; boundary=B0EC8D07-EBF1-4EA7-966C-E492A9F2C36E

--B0EC8D07-EBF1-4EA7-966C-E492A9F2C36E
Content-Disposition: form-data; name="user";
Content-Type: application/xml; charset=UTF-8

<user><!-- your user xml --></user>
--B0EC8D07-EBF1-4EA7-966C-E492A9F2C36E
Content-Disposition: form-data; name="file"; filename="A551A700-46D4-470A-86E7-52AD2B445847.dat"
Content-Type: application/octet-stream

/// FILE DATA
--B0EC8D07-EBF1-4EA7-966C-E492A9F2C36E--


Answer 2:

我已成功地解决问题

端点例如:

@PostMapping("/")
public Document create(@RequestPart Document document,
                       @RequestPart(required = false) MultipartFile file) {
    log.debug("#create: document({}), file({})", delegation, file);
    //custom logic
    return document;
}

例外:

"error_message": "Content type 'application/octet-stream' not supported"

异常是从下一个方法抛出:

org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(HttpInputMessage,MethodParameter,Type)

解:

我们必须创建自定义转换器@Component,它实现HttpMessageConverterHttpMessageConverter和知道MediaType.APPLICATION_OCTET_STREAM。 对于简单的解决方法是足够的扩展AbstractJackson2HttpMessageConverter

@Component
public class MultipartJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {

/**
 * Converter for support http request with header Content-Type: multipart/form-data
 */
public MultipartJackson2HttpMessageConverter(ObjectMapper objectMapper) {
    super(objectMapper, MediaType.APPLICATION_OCTET_STREAM);
}

@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
    return false;
}

@Override
public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) {
    return false;
}

@Override
protected boolean canWrite(MediaType mediaType) {
    return false;
}
}


Answer 3:

你有没有尝试过

ResponseEntity<List<Map<String, String>>> createUser(
        @RequestPart("file") MultipartFile file, @RequestBody(required=false) User user) {

要么

ResponseEntity<List<Map<String, String>>> createUser(
        @RequestPart("file") MultipartFile file, @RequestParam(required=false) User user) {

如果这不起作用,您能不能告诉我们mapping.xml



文章来源: @RequestPart with mixed multipart request, Spring MVC 3.2