首页 > 解决方案 > 如何使spring mvc将json数组转换为arraylist(带上传文件的表单提交)?

问题描述

我正在使用下面的代码将带有文件上传的表单提交到后端 spring mvc 控制器。

function submit() {
    var formData = new FormData();
    var fileField = document.querySelector("input[type='file']");


    formData.append('mail', document.getElementsByName('mail')[0].value);
    formData.append('applicationName', 'myapp');

    // please remove the attachment if no file attached
    formData.append('attachment', fileField.files[0]);

    const releaseNotes = [{
        type: "java",
        overview: "good"
    },
    {
        type: "java2",
        overview: "good2"
    }]

    formData.append('releaseNotes', releaseNotes)

    fetch('springapi/addform', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .catch(error => console.error('Error:', error))
        .then(response => console.log('Success:', JSON.stringify(response)));

}

控制器如下所示。

@RequestMapping(value = "add", method = RequestMethod.POST)
public @ResponseBody UserInfo save( UserInfo userInfo, HttpServletRequest request) throws RestException {

    myService.save(userInfo);

    return  userInfo;
}

该对象如下所示。

public class UserInfo {
    private Long ID;
    private String mail;
    private String applicationName;
    private List<ReleaseNote> releaseNotes;

    }

当我运行这个演示时,它会报告以下异常。

default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'releaseNotes'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.xxx.rest.jpa.entity.ReleaseNote] for property 'releaseNotes[0]': no matching editors or conversion strategy found] (.java:24) in http-bio-8080-exec-1

ps:如果不需要使用fileupload,我可以使用RestController解决这个问题,并通过下面的方式将json发布到后端。

fetch(url,
  {method: 'post',
    headers: {
      'Accept': 'application/json',
      'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'},
    body: json    })

但是由于有文件上传,所以我必须使用FormData而不是将 json 传递给后端。如何解决这个问题?谢谢。

标签: springspring-mvc

解决方案


推荐阅读