Thursday, 4 July 2013

Multiple File Uploading With Spring

//#####################################Screen Shot









//##################################### 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

 <script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript">
var i=1;
$(document).ready(function(){
$('#add').click(function(){
$('#files').append('<input type="file" name="file['+i+']"/><br>');
i++;
});
$('#upload').click(function(){
$('#files').append('<input type="hidden" name="count" value='+i+'>');
console.log(i);
});
});
</script>

 -------------------------------------------------------------------------------------------------

<p>Click Add Button To Browse More Files</p>
<form action="uploadMultipleFiles" enctype="multipart/form-data" method="post">
<div id="files">
<input type="file" name="file[0]" />
<input type="submit" value="upload" id="upload"/>
<input type="button" id="add" value="Add" /><br>
</div>
</form>


//##################################### Controller Code

 @RequestMapping("/uploadMultipleFiles")
public String uploadFiles(HttpServletRequest request) throws IOException{

System.out.println("inside upload multiple files..");
int total=Integer.parseInt(request.getParameter("count"));
//System.out.println(total);
MultipartHttpServletRequest req=(MultipartHttpServletRequest)request;
for(int i=0;i<total;i++){
MultipartFile files=req.getFile("file["+i+"]");
String filenameToCreate="D:\\harsh.patel\\SpringFileUpload\\UploadedFiles\\"+files.getOriginalFilename();
System.out.println(filenameToCreate);
File file = new File(filenameToCreate);
FileUtils.writeByteArrayToFile(file, files.getBytes());
}
System.out.println("after upload multiple files");
return "result";

}
 
Post a Comment