Thursday, 4 July 2013

Simple File Upload in Spring



//##################################### Maven Dependency

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

//##################################### Jsp Code

<form action="uploadRequest" enctype="multipart/form-data" method="post">
<input type="file" id="file" name="file"/>
<input type="submit" value="upload" />
</form>

//######################################  Controller Code
@RequestMapping("uploadRequest")
public String upload(HttpServletRequest request) throws IOException{
System.out.println("inside upload");
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
MultipartFile files = req.getFile("file");
String filenameToCreate="Path Up to Folder\\"+files.getOriginalFilename();
//(Don't forgot to put \\ )
System.out.println(filenameToCreate);
File file = new File(filenameToCreate);
FileUtils.writeByteArrayToFile(file, files.getBytes());
System.out.println("after upload");
return "result";
}
Post a Comment