Issue
I am using Spring-MVC 3.0, and in my application, I am sending some information with multiple attachments, and each one of these files have title, Id etc. So, I made one DTO as follows
public class MyDTO {
Long id;
Integer age;
MultipartFile infoFile;
// getter setter
I am just creating one JSON
object according to the above DTO class in my JS
file.
Here is my Controller
mapping:
@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();
}
But I am getting following errors:
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"])
Solution
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
{"File" : "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");
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 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));
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).
Answered By - Avinash