JsonMappingException:无法构造CommonsMultipartFile的实例 [英] JsonMappingException: Can not construct instance of CommonsMultipartFile
问题描述
我使用Spring-MVC 3,在我的应用程序中,我发送一些信息
有多个附件,每个文件都有一个标题,Id等等。所以,我做了一个DTO如下
I using Spring-MVC 3, and in my application, I am sending some information with multiple attachments and each one this files have one title, Id etc. So, I made one DTO as follows
public class MyDTO {
Long id;
Integer age;
MultipartFile infoFile;
// getter setter
我只是创建一个 JSON
根据我的 JS
文件中的上述DTO类对象。
I am just creating one JSON
object according to above DTO class in my JS
file.
这里是我的控制器
映射:
@RequestMapping(value = "/saveInfo", method = RequestMethod.POST)
public @ResponseBody String saveInfo(
@RequestParam(value = "data", required = true) String stdData,
@RequestParam(value = "fileData", required = false) MultipartFile[] files,
HttpSession session,HttpServletRequest request) {
MyDTO dto;
try {
dto = mapper.readValue(stdData, new TypeReference<MyDTO>() {});
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
但我收到以下错误:
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of org.springframework.web.multipart.commons.CommonsMultipartFile,
problem: no suitable creator method found to deserialize from JSON String
at [Source: java.io.StringReader@19747c9; line: 1, column: 336] (through reference chain: com.avi.dto.MyDTO["hbvFile"])
推荐答案
其实我找到了自己的答案。我们无法直接在JSON对象中发送文件。 文件
对象不保存文件,它保存文件的路径,即。 C:/hi.txt。如果这就是我们在JSON中放入的内容,它将产生
Actually I find the answer for myself. We can't send file directly in JSON object. A File
object doesn't hold a file, it holds the path to the file, ie. C:/hi.txt. If that's what we put in our JSON, it'll produce
{文件:C:/hi.txt}
它不包含文件内容。所以我们不妨直接放置文件路径
It won't contain the file content. So we might as well just put the file path directly
JSONObject my_data = new JSONObject();
my_data.put("User", "Avi");
my_data.put("Date", "22-07-2013");
my_data.put("File", "C:/hi.txt");
如果您尝试使用JSON上传文件,一种方法是从中读取字节数Java 7的NIO文件
If you're trying to do a file upload with JSON, one way is to read the bytes from the file with Java 7's NIO
byte[] bytes = Files.readAllBytes(file_upload .toPath());
Base64对这些字节进行编码,并将它们作为字符串写入JSONObject中。使用Apache Commons Codec
Base64 encode those bytes and write them as a String in the JSONObject. Using Apache Commons Codec
Base64.encodeBase64(bytes);
my_data.put("File", new String(bytes));
有 94个Unicode
字符可以是根据JSON规范表示为一个字节(如果您的JSON以UTF-8格式传输)。
There are 94 Unicode
characters which can be represented as one byte according to the JSON spec (if your JSON is transmitted as UTF-8).
这篇关于JsonMappingException:无法构造CommonsMultipartFile的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!