Ajax File Upload

Ajax File Upload

You might have seen Ajax File Uploading in some sites. The basic idea is to upload a file without refreshing the page. Some sites go even further by providing details on how much percentage is uploaded, etc. It is very easy to achieve this effect using javascript.

First off, I did not like using the term 'Ajax' when describing this method. But there is no other word that can be used. And this method fits within my definition of Ajax - "Sending or receiving data from the server without refreshing the page.". So I will name this method Ajax file upload.

Theory

The basic idea behind this effect is to redirect a form's action into a hidden IFrame. So, when the form with the file field is submitted, the result will appear in a IFrame. But since it is hidden, the user will not see it. This effect is achieved using the 'target' attribute of the Form tag.



id="upload_target" name="upload_target" src="http://www.openjs.com/articles/ajax/ajax_file_upload/" style="width: 100px; height: 100px; border: 1px solid rgb(204, 204, 204);">

See the small squire? That is the IFrame. Typically, it will be hidden.

Code

(X)HTML

<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.php">
<input name="file" id="file" size="27" type="file" /><br />
<input type="submit" name="action" value="Upload" /><br />
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>

JavaScript

function init() {
	document.getElementById('file_upload_form').onsubmit=function() {
		document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
	}
}
window.onload=init;

PHP

This should be in upload.php - the action of the form.

<?php
include('../../../common.php');
upload('file','.','txt,jpg,jpeg,gif,png');

The code to upload the file must be given here. I used one of my custom functions to upload the file - it is not a native PHP function. Needless to say, this is not restricted to PHP - you can use any server side language here.

Update: Part two - Ajax File Upload Response Handling


//Some funny comments:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值