最近写了不少别人写过的东西,哎。
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<form id="J_myUploadForm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileField" id="fileField" />
</form>
<input type="button" value="ajaxFileUpload" id="btn"/>
<script src="ajaxFileUpload.js"></script>
<script>
var btn = document.getElementById('btn');
btn.onclick = function(){
ajaxFileUpload({
id:'fileField',
callback:function(){
var src = this.responseText;
var img = document.createElement('img');
img.src = src;
document.body.appendChild(img);
}
});
}
</script>
</body>
</html>
PHP
<?php
move_uploaded_file($_FILES["fileField"]["tmp_name"], "upload/" . $_FILES["fileField"]["name"]);
echo "upload/" . $_FILES["fileField"]["name"];
?>
JS
/*
作者:天涯
QQ:63886829
eMail:flyinksy@gmail.com
说明:ajax文件上传
*/
var ajaxFileUpload = function(opts){
return new ajaxFileUpload.prototype.init(opts);
};
ajaxFileUpload.prototype = {
init:function(opts){
var set = this.extend({
url:'result.php',
id:'fileId',
callback:function(){}
},opts || {});
var _this = this;
var id = +new Date();
var form = this.createForm(id),frame = this.createIframe(id,set.url);
var oldFile = document.getElementById(set.id)
var newFile = oldFile.cloneNode(true);
var fileId = 'ajaxFileUploadFile'+id;
oldFile.setAttribute('id',fileId);
oldFile.parentNode.insertBefore(newFile,oldFile);
form.appendChild(oldFile);//注意浏览器安全问题,要将原文件域放到创建的form里提交
form.setAttribute('target',frame.id);//将form的target设置为iframe,这样提交后返回的内容就在iframe里
form.setAttribute('action',set.url);
setTimeout(function(){
form.submit();
if(frame.attachEvent){
frame.attachEvent('onload',function(){_this.uploadCallback(id,set.callback);});
}else{
frame.onload = function(){_this.uploadCallback(id,set.callback);}
}
},100);
},
/*
创建iframe,ie7和6比较蛋疼,得像下面那样创建,否则会跳转
*/
createIframe:function(id,url){
var frameId = 'ajaxFileUploadFrame'+id,iFrame;
var IE = /msie ((\d+\.)+\d+)/i.test(navigator.userAgent) ? (document.documentMode || RegExp['\x241']) : false,
url = url || 'javascript:false';
if(IE && IE < 8){
iFrame = document.createElement('<iframe >return target;
}
};
ajaxFileUpload.prototype.init.prototype = ajaxFileUpload.prototype;