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.
Example.
ajaxfileupload.jsp
<html>
<body>
<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”/>
</form>
</body>
</html>
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 – http://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax Example – http://manikandanmv.wordpress.com/2008/09/29/ajax-example/
Tags: AJAX, ajax basics, ajax file upload, ajax send file, file upload, file upload to server, iframe