Ajax File Upload

Normally its not easy to upload a file in ajax request. Even form input parameters are sending manually, you can read here for more details. With the help of iframe its possible for uploading a file(any format : .txt, .jpg,..) to the server without refreshing the entire page as like ajax. Lets see the example of how to do.



<iframe id=”uploadFileFrameId” src=“javascript:false;” name=”uploadFileFrame”  height=”0″ width=”0″ frameborder=”0″ scrolling=”no”></iframe>
<form name=”uploadFile” enctype=”multipart/form-data” action=”/readFile.do” method=”POST” target=”uploadFileFrame” onsubmit=”validate();”>
<input type=”file” name=”filename” value=””/>
<input type=”submit” name=”submit” value=”upload file”/>

Invisible or Hidden iframe is used to upload a file to server. Thats the trick.! Lets explain each attribute of iframe & form tag to understand clearly.

iframe attributes

name – name of which uniquely identify the iframe. In our case its called “uploadFileFrame”
src – source file to show in iframe. In IE browser asks security popup msg when iframe src is empty, to solve this problem you can use javascript:false
height, width – define height & width of iframe, In our case it should not visible so we set value 0 for both.
frameborder – define to display iframe border, 0 – noborder
scrolling – define scroll bars. no – represent no scroll bar.

form attributes

name – define unique form name
target – where to open the file.
action – url to send data to server
enctype – define mime type. for file upload use multipart/form-data

In the above example, i used form attribute target equal to iframe name(target=”uploadFileFrame”) which means that iframe will take care of sending/uploading file to server when you submit a form.

New to Ajax, read below referred pages to learn basics.

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/

Ajax Example – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/

Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: