我是JQuery的新手,我正在尝试做一些异步多部分表单上传。表单由少量数据字段和文件类型组成。我已经设置了服务器端代码(Spring),如下所示:
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody
Upload multipleSave(MultipartHttpServletRequest request)
{
Upload upload = new Upload();
Iterator<String> iterator = request.getFileNames();
while (iterator.hasNext())
{
MultipartFile file = request.getFile(iterator.next());
try
{
System.out.println(MessageFormat.format("File Length: {0}", Arrays.toString(file.getBytes())));
System.out.println("File Type: " + file.getContentType());
upload.setContent(file.getBytes());
upload.setDocId(id++);
upload.setError(null);
upload.setName(file.getName());
upload.setSize(file.getSize());
fileList.put(upload.getDocId().toString(), upload);
} catch (Exception e)
{
System.out.println("Error occurred: " + e);
upload.setError("500: Something went wrong!");
}
}
return upload;
}
和客户端代码如下:
function processFileUpload()
{
console.log("fileupload clicked");
var formData = new FormData();
formData.append("file", files[0]);
$.ajax({dataType: 'json',
url: "/SpringJqueryFileUpload/upload",
data: formData,
type: "POST",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (result) {
alert('success' + JSON.stringify(result));
},
error: function (result) {
alert('error' + JSON.stringify(result));
}
});
}
当我提交时,服务器会回复:
java.lang.IllegalArgumentException: No converter found for return value of type: class com.upload.model.Upload
我想知道错误。我可以在这里遗漏一些东西吗?
答案 0 :(得分:2)
我会尝试将您的注释更改为:
@RequestMapping(method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
并确保在您的路径上正确使用Jackson(Spring用于JSON序列化)。另外,请确保您的Upload
类可序列化,例如不是private
或类似的东西。如果它只是一个普通的Java bean类型,它应该没问题。
最后,如果这不起作用,您可以使用以下内容打开Spring调试日志:
log4j.category.org.springframework.web=ALL
在log4j.properties文件中。