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

[email protected]

About Author

Author Image
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.

Request for Proposal

Name is required

Comment is required

Sending message..