2014-07-08 48 views
1

我使用Spring-MVC 3,并在我的应用程序中,我发送一些信息 与多个附件,每个文件有一个标题,Id等。所以,我做了一个DTO如下JsonMappingException:无法构建CommonsMultipartFile的实例

public class MyDTO { 

Long id; 

Integer age; 

MultipartFile infoFile; 

// getter setter 

我按照上面DTO类在我JS文件只是创造一个JSON对象。

这是我Controller映射:

@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: [email protected]; line: 1, column: 336] (through reference chain: com.avi.dto.MyDTO["hbvFile"]) 
+0

它可能需要一个没有参数的构造函数,'CommonsMultipartFile'没有一个。 –

+0

你可以展示你的'JSON'看起来像什么吗? –

回答

2

其实我觉得我自己的答案。我们无法直接在JSON对象中发送文件。 A File对象不包含文件,它保存文件的路径,即。 C:/hi.txt。如果这就是我们把我们的JSON,它会产生

{"File" : "C:/hi.txt"}

它将不包含文件内容。所以我们干脆把文件路径直接

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

byte[] bytes = Files.readAllBytes(file_upload .toPath()); 
文件中读取的字节

Base64对这些字节进行编码并将它们作为字符串写入JSONObject中。使用Apache共享编解码器

Base64.encodeBase64(bytes); 
my_data.put("File", new String(bytes)); 

有可根据JSON规范(如果您的JSON作为UTF-8传送)被表示为一个字节94 Unicode字符。