SpringMVC FileUpload with ajax & JQuery
If you want to upload a file in a SpringMVC application with ajax you need to do following things
Server Side
On server side there are many ways but MultipartHttpServletRequest is easiest way to do that. On server side you need some logic to handle the file uploaded.For this we will be using apache commons utilities commons-fileupload and commons-io . Include these two jars in the class path of your project. commons-fileupload-1.3.1.jars and commons-io-2.4.jar. for me it is C:\TestProject\WebContent\WEB-INF\lib. And one more jar com.fasterxml.jackson.core.jar for json conversion if required.
As we have included necessary jars to handle the uploaded file now we will write the Controller which will have the methods to actually handle the upload.
package com.faisalbhagat.web.controller;
@Controller
@RequestMapping(value = { "" })
public class UploadController {
@RequestMapping(value = "/uploadMyFile", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(MultipartHttpServletRequest request)
throws Exception {
Iterator<String> itrator = request.getFileNames();
MultipartFile multiFile = request.getFile(itrator.next());
try {
// just to show that we have actually received the file
System.out.println("File Length:" + multiFile.getBytes().length);
System.out.println("File Type:" + multiFile.getContentType());
String fileName=multiFile.getOriginalFilename();
System.out.println("File Name:" +fileName);
String path=request.getServletContext().getRealPath("/");
//making directories for our required path.
byte[] bytes = multiFile.getBytes();
File directory= new File(path+ "/uploads");
directory.mkdirs();
// saving the file
File file=new File(directory.getAbsolutePath()+System.getProperty("file.separator")+picture.getName());
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(file));
stream.write(bytes);
stream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("Error while loading the file");
}
return toJson("File Uploaded successfully.")
}
public String toJson(Object data)
{
ObjectMapper mapper=new ObjectMapper();
StringBuilder builder=new StringBuilder();
try {
builder.append(mapper.writeValueAsString(data));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return builder.toString();
}
}
<bean id="multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
@ResponseBody
public String handleFileUpload(MultipartHttpServletRequest request)
throws Exception {
Iterator<String> itrator = request.getFileNames();
MultipartFile multiFile = request.getFile(itrator.next());
try {
// just to show that we have actually received the file
System.out.println("File Length:" + multiFile.getBytes().length);
System.out.println("File Type:" + multiFile.getContentType());
String fileName=multiFile.getOriginalFilename();
System.out.println("File Name:" +fileName);
String path=request.getServletContext().getRealPath("/");
//making directories for our required path.
byte[] bytes = multiFile.getBytes();
File directory= new File(path+ "/uploads");
directory.mkdirs();
// saving the file
File file=new File(directory.getAbsolutePath()+System.getProperty("file.separator")+picture.getName());
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(file));
stream.write(bytes);
stream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new Exception("Error while loading the file");
}
return toJson("File Uploaded successfully.")
}
public String toJson(Object data)
{
ObjectMapper mapper=new ObjectMapper();
StringBuilder builder=new StringBuilder();
try {
builder.append(mapper.writeValueAsString(data));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return builder.toString();
}
}
We will Register “CommonsMultipartResolver” in our TestProject-servlet.xml to tell Spring to use commons-upload library to handle the file upload form. The rest is just normal bean declaration.
it will be like this
<bean id="multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
Client Side
we are implementing client side with html,jquery and javascript
This is our index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$("#subbutton").click(function(){
processFileUpload();
});
$("#loader1").on('change',prepareLoad);
var files;
function prepareLoad(event)
{
console.log(' event fired'+event.target.files[0].name);
files=event.target.files;
}
function processFileUpload()
{
console.log("fileupload clicked");
var oMyForm = new FormData();
oMyForm.append("file", files[0]);
$
.ajax({dataType : 'json',
url : "${pageContext.request.contextPath}/uploadMyFile",
data : oMyForm,
type : "POST",
enctype: 'multipart/form-data',
processData: false,
contentType:false,
success : function(result) {
alert('success'+JSON.stringify(result));
},
error : function(result){
alert('error'+JSON.stringify(result));
}
});
}
});
</script>
</head>
<body>
<input type="file" name="loader1" id="loader1" />
<input type="button" id="subbutton" value="Upload"/>
</body>
</html>
This is our index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$("#subbutton").click(function(){
processFileUpload();
});
$("#loader1").on('change',prepareLoad);
var files;
function prepareLoad(event)
{
console.log(' event fired'+event.target.files[0].name);
files=event.target.files;
}
function processFileUpload()
{
console.log("fileupload clicked");
var oMyForm = new FormData();
oMyForm.append("file", files[0]);
$
.ajax({dataType : 'json',
url : "${pageContext.request.contextPath}/uploadMyFile",
data : oMyForm,
type : "POST",
enctype: 'multipart/form-data',
processData: false,
contentType:false,
success : function(result) {
alert('success'+JSON.stringify(result));
},
error : function(result){
alert('error'+JSON.stringify(result));
}
});
}
});
</script>
</head>
<body>
<input type="file" name="loader1" id="loader1" />
<input type="button" id="subbutton" value="Upload"/>
</body>
</html>
First of all we add include of jquery in head section
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
Then in the body section we will declare input with type="file" to select the file and a button to actually upload the file.
<input type="file" name="loader1" id="loader1" />
<input type="button" id="subbutton" value="Upload"/>
After that we will be adding a 'change' event handler for the input "loader1" as follows
$("#loader1").on('change',prepareLoad);
var files;
function prepareLoad(event)
{
console.log(' event fired'+event.target.files[0].name);
files=event.target.files;
}
it is storing selected file in the global variable named files. On the click event of button processFileUpload() is called which actually sends the file to server. we are sending the file packed in the FormData Object.
Don't work!
ReplyDeleteYeap...don't work, because the "boundary" variable isn't included on the request, according to the spec: https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
ReplyDeleteI really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in AJAX, kindly contact us http://www.maxmunus.com/contact
ReplyDeleteMaxMunus Offer World Class Virtual Instructor led training on AJAX. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
For Demo Contact us.
Nitesh Kumar
MaxMunus
E-mail: nitesh@maxmunus.com
Skype id: nitesh_maxmunus
Ph:(+91) 8553912023
http://www.maxmunus.com/