我正在使用以下代码将带有fileupload的表单提交到后端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传递给后端。如何解决这个问题?谢谢。