Uploading Files On Server In Grails using JQuery Ajax
Posted By : Sanjay Saini | 17-Nov-2014
Hi friends ,now I'm going to explain you easiest way of uploading Files in grails with Ajax. In this demo example,I'm using csv file for uploading .
Step-1 : You need to do is set up your HTML form that will allow the user to select the file that they wish to upload.
HTML code :
Step-2 : Write Jquery ajax code for uploading file to the server.
Jquery ajax code(Client-side code)
$('#demoform').submit(function(e) { e.preventDefault(); var file = $('#file').val() var jForm = new FormData(); jForm.append("file", $('#file').get(0).files[0]); $.ajax({ url: "uploadFile", type: "POST", data: jForm, mimeType: "multipart/form-data", contentType: false, cache: false, processData: false, success: function(data) { //write code here that you want to doing after successfully file upload. } }); } })
Step 3: Write Server code that used to transfer file content to a file. In grails that code write in controller.
Grails Controller Code (Server Side code)
Class UploadController{ def uploadFile(){ def fileData =params.file File file=new File("demo.csv") if(file.exists()) fileData.transferTo(file) else{ file.createNewFile() fileData.transferTo(file) } render "Uploaded Successfully" } }
Thanks
Sanjay Saini
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sanjay Saini
Sanjay has been working on web application development using frameworks like Java, groovy and grails. He loves listening to music , playing games and going out with friends in free time.