Submit form data and file using Ajax with jQuery in Grails
Posted By : Abhimanyu Singh | 27-Jul-2013
I have recently work on a grails project which has requirement of submitting a form which has form data and file using ajax . In this blog I have shared how I approach this problem and get it done.
Here is my GSP form
Here is my Ajax code
$('.clickClass').click(function(){
var oData = new FormData(document.forms.namedItem("fileinfo"));
var url="${createLink(controller:'uploadAjax',action:'uploading')}";
$.ajax({
url:url,
type:'POST',
data:oData,
processData: false, // tell jQuery not to process the data
contentType: false ,
success:function (req) {
alert(req);
}
});
});
I have used FormData to submit file along with other input field . In form tag , I have used the enctype property “multipart/form-data”.
In ajax call I have created object of FormData
var oData = new FormData(document.forms.namedItem("fileinfo"));
and pass it to data in Ajax call .
You have seen property I have used in ajax call is
processData: false, // tell jQuery not to process the data
contentType: false , //forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it
On submitting the form on controller you will get both file name you have provided and file which you have uploaded .
Here is output
[name:myFIle, uploadField:org.springframework.web.multipart.commons.CommonsMultipartFile@26284112, action:uploading, controller:uploadAjax]
Now in controller I have simply read the file and save it to desire location . Here is the code of “uploading action” which is called by ajax call .
def uploading={
println params
fileUploader(params.uploadField)
render params.name
return
}
uploading action called the fileUploader function which will read the input stream and will save the file for you .
def fileUploader(def file){
Random randomGenerator = new Random()
int randomInt = randomGenerator.nextInt(1000000)
def docName = randomInt+file?.getOriginalFilename()
log.debug"Random no: "+randomInt
InputStream is = file?.getInputStream()
OutputStream os = new FileOutputStream("/home/abhimanyu/Desktop/"+docName) //file path
log.debug"Image Size: "+file?.getSize()
byte[] buffer = new byte[file?.getSize()]
int bytesRead
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead)
}
is.close()
os.close()
return docName
}
Thanks !
Abhimanyu
About Author
Abhimanyu Singh
Abhimanyu is an seasoned technologist . He always keeps himself ahead in embracing and adapting new technologies/frameworks to solve business problems. He specialise in Blockchain technology , Video Content Management & enterprise software .