spring - 如何使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 传递给后端。如何解决这个问题?谢谢。
解决方案
推荐阅读
- javascript - 如何使用 javascript 捕获包含值的 html 文档
- python - 为什么 SymPy 不简化表达式?
- react-native - 如何导出 Appcontainer 并在另一个 Screenpage 中导入?
- database - Elasticsearch 和 Neo4j 哪个更适合这种场景?
- python - python setup_tools install_required
- python-2.7 - 为什么 conda 找不到本地虚拟环境的正确 PYTHONPATHS?
- semantic-ui-react - 为图标链接添加 onClick?
- c++ - QT“Tick”小部件循环
- webdriver-io - 当我运行 wdio-runner 时,我收到“wdio-cli:无法识别来自工作人员的消息”警告消息
- mongodb - mongod.service 启动失败: Unit mongod.service not found., 找不到mongod.service?