I am uploading a picture using form-data
taking the picture from the Client's PC to Spring MVC Server.
Update Page:
<!DOCTYPE html > <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring MVC - Upload File</title> </head> <body> <form id="form1" method="post" action="/upload" enctype="multipart/form-data" accept-charset="utf-8"> <!-- File input --> <input name="file" id="file" type="file" /><br/> <input type="submit" value="Upload" /> </form> </body> </html>
And this is the Spring Controller
@RequestMapping(value = "upload", method = RequestMethod.POST) public @ResponseBody String provaUpdate(MultipartHttpServletRequest request,Principal p,HttpServletResponse response)throws IOException { String result=""; LocalFileManager mLocalFileManager = LocalFileManager.get(); Iterator<String> iterator = request.getFileNames(); while(iterator.hasNext()) { System.out.println("iterator.next()="+iterator.next()); } System.out.println("request.getFileMap().isEmpty()??"+request.getFileMap().isEmpty()); // mLocalFileManager.saveLocalData(g,g.getPicturesCount(), request.getFile("new").getInputStream()); return result; }
So, when i run that, it just prints:
request.getFileMap().isEmpty()??true
Then, no Files seems to be uploaded, but if I get the request.getInputStream()
I can write a TXT File showing that:
------WebKitFormBoundaryWG8vA5PuTFFxPBqK Content-Disposition: form-data; name="file"; filename="1.jpg" Content-Type: image/jpeg �� JFIF ��ICC_PROFILE 蠠 mntrRGB XYZ ٠ $ acsp �� ӭ )B9 desc D ybXYZ bTRC Ԡ dmdd ࠠ ɧXYZ h gTRC Ԡ lumi | meas //(Symbols) Long ETC, so the picture is sent !! ------WebKitFormBoundaryWG8vA5PuTFFxPBqK--
So, seems that the picture is sent correctly but the MultipartHttpServletRequest
is not able to get the File.
Which is my mistake?
The mistake was that i am working with Thymeleaf, so the form is different.
It is solved changing that:
1- Create a class that contains a MultipartFile, like this:
public class Images { MultipartFile image; public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } }
2- The correct form code for a Spring Server working with Thymeleaf:
<form id="myform" action="#" th:action="@{/upload}" th:object="${Images}" method="POST" modelAttribute="Images" enctype="multipart/form-data"> <input type="file" th:field="${Images.image}" name="file"/> <input type="submit" value="Upload"/> </form>
And finally the correct Controller method:
@RequestMapping(value = "upload", method = RequestMethod.POST) public String addVocabularyValadate( @ModelAttribute("Images") Images images,BindingResult bindingResult, Model model) throws IOException { System.out.println("inputstream Nombre!"+images.getImage().getOriginalFilename()); if(bindingResult.hasFieldErrors() == true) return "error"; else return "upload OK!"; }