php文件上传是非常简单的啦,在html页面有一个表单,form标签有一个属性设置成enctype="multipart/form-data"
<input>标签的 type="file" 属性规定了应该把输入作为文件来处理。举例来说,当在浏览器中预览时,会看到输入框旁边有一个浏览按钮。-data"
html的部分
<!DOCTYPE html>
<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 action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file"/>
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
php地方也很简单通过使用 PHP 的全局数组 $_FILES,你可以从客户计算机向远程服务器上传文件。
- $_FILES["file"]["name"] - 被上传文件的名称
- $_FILES["file"]["type"] - 被上传文件的类型
- $_FILES["file"]["size"] - 被上传文件的大小,以字节计
- $_FILES["file"]["tmp_name"] - 存储在服务器的文件的临时副本的名称
- $_FILES["file"]["error"] - 由文件上传导致的错误代码
还有一个东西move_uploaded_file 可以讲上传文件移动到某个目录下面,因为php会把上传的文件放到一个临时的文件里面,所以要把文件移动到制定的文件夹
php代码
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
}
?>
这是最简单的了 有跳转 刷新页面 ,没有进度条 没有文件的判断 什么都没有
然后既然是上传,肯定会对上传文件的大小有限制,在php.ini里面 upload_max_filesize = 30M 这里可以限制上传文件的大小, post_max_size = 33M可以设置post的最大的数据
有时候希望上传的是不刷新,可以借助iframe,将form的target指向iframe的name;这个就不会刷新了,如何知道上传文成了??可以这样做,因为执行的php在iframe里面执行的,就可以放回一段js代码比如"<script>top.upCallback({valid:1,message:'成功了'})</script>" 它调用父页面的全局函数upCallback,所以在上传页面定义个upCallback做为上传完成的回调
html部分
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<iframe name="upframe"></iframe>
<form action="upload_file.php" method="post" enctype="multipart/form-data" target="upframe">
<label for="file">Filename:</label>
<input type="file" name="file"/>
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
<script>
function upCallback(obj){
if(!obj)
return;
if(obj.valid==1){
alert(obj.message);
}else{
alert("失败");
}
}
</script>
</html>
php部分
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "<script>top.upCallback({valid:0})</script>" ;
}
else
{
$is = move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
if($is){
echo "<script>top.upCallback({valid:1,message:'成功了'})</script>" ;
}else{
echo "<script>top.upCallback({valid:0})</script>" ;
}
}
?>
在表单元素里面还是<input type="file"> 在高级点的浏览器里面都支持input.files(它是以个数组,里面可以保存选择的文件的相关信息,比如文件大小,文件类型 ) 这个东西是html5的api哟files的介绍这里有点 html5 file api 介绍这里有点 其实我找到的介绍都不是很仔细,还是要自己动手多试
另外一个比较强大的东西就 xhr了,就是就是ajax提交的那个东西(html5上传是ajax提交的). html5可以给xhr绑定事件了,比如progress(可以看上传了多少), abort(中断) load(上传完成了)一些xhr相关东西的介绍 一些xhr相关东西的介绍 找了一下 还真没找到介绍的比较详细的xhr新属性的东西
既然是ajax提交,要上传的东西怎么取到了,都知道xhr发送数据到服务端是通过send方法,参数传数据 比如xhr.send(data),data就是数据了.
html5上传要到一个新对象FormData FormData介绍 var fd = new FormData(document.getElementById('form1')); 就可以格式化数据了
在php端就是取值的时候
我测试了几次 返现取出根据不同的浏览器有关
在ff中 用$_FILES["fileToUpload"] fileToUpload是input的name
还在chrome中 用$_FILES["Filedata"] 取值
在 Safari中发现 $_FILES["Filedata"] $_FILES["fileToUpload"]都能娶到值 哎
取的是$_FILES["fileToUpload"]而不是$_FILES["file"];
xhr绑定的是load是上传完成了, 但是服务端还要处理相关的东西,所以最后的回调还是要写在xhr.onreadystatechange里面找服务器处理完后来写回调(因为有可能上传成功了,但是转移目录,或者操作数据库,或者其他n多种情况失败了)
html部分
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<body>
<style type="text/css">
#progress{ height:20px; border:1px solid #CCC; width:100px; display:none;}
#bar{ width:0; height:20px; background-color:#900;}
</style>
<form id="form1" enctype="multipart/form-data" method="post" action="uu.php">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onChange="fileSelected();"/>
</div>
<div class="row">
<input type="button" onClick="uploadFile()" value="Upload" />
</div>
<table width="310" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100"> <div id="progress"><div id="bar"></div></div></td>
<td><div id="b"></div></td>
</tr>
</table>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
</form>
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size>1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile() {
var xhr = new XMLHttpRequest();
var fd = new FormData(document.getElementById('form1'));
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if((xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 ) //返回码两百内表示陈宫了 304表示告诉浏览器读缓存
var o = eval("("+xhr.responseText+")");
if(o.valid == 1){
uploadComplete();
alert("上传成功...");
}
}
}
xhr.open("POST", "upload.php");
xhr.send(fd);
}
function uploadProgress(e){
var progress = document.getElementById("progress");
progress.style.display = "block";
var bar = document.getElementById("bar");
var b = document.getElementById("b");
if(e.lengthComputable){
var c = parseInt(((e.loaded)/(e.total))*10000)/10000;
bar.style.width = parseInt(c*100)+"px";
b.innerHTML = c*100+"%";
}
}
function uploadComplete(e){
document.getElementById("progress").style.display = "block";
bar.style.width ="100px";
b.innerHTML = "100% upadate ok";
}
function uploadFailed(){
}
function uploadCanceled(){
}
</script>
</body>
</html>
php部分
<?php
/*
print_r($_FILES);
Array
(
[fileToUpload] => Array
(
[name] => demo.htm
[type] => text/html
[tmp_name] => C:\wamp\tmp\php4F1.tmp
[error] => 0
[size] => 29313
)
)
*/
if ($_FILES["fileToUpload"]["error"] > 0)
{
echo "{valid : 0 , message:'失败了'}" ;
}
else
{
$is = move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],"upload/" . $_FILES["fileToUpload"]["name"]);
if($is){
echo "{valid : 1 , message:'成功了'}" ;
}else{
echo "{valid : 0 , message:'上传成功 转移目录失败了 '}" ;
}
}
?>
没啥好说的 懂as就行
做了几天上传的测试 发现
upload_max_filesize upload_max_filesize都做了上限限制 但是还是可能传文件传不上去
这是可以看看是不是 memory_limit的问题 把它设置大点也许就解决了
部分html js代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<style>
#c{ text-align:left; font-size:12px;}
#c div.btn{ width:90px; height:30px; border:1px solid #9C9C9B; background:url(btn.gif) 0 0 no-repeat;}
#c div.btn:hover{ background:url(btn.gif) 0 -30px no-repeat}
#c .file{width:90px; height:30px; opacity:0; cursor:pointer;}
#c .bar{
width:350px; display:none; padding:0 5px 5px; background:#FFFFE1; border:1px solid #9C9C9B; margin-top:10px;
}
#c .list{ overflow:hidden; margin-top:5px; position:relative}
#c .loadbar{ width:100px; height:10px; overflow:hidden; border:1px solid #9C9C9B; float:left; margin-right:5px;}
#c .bai{ float:left; display:inline-block;_zoom:1;*display:inline; width:35px; margin-left:10px; }
#c .info{float:left; height:14px; display:inline-block;_zoom:1;*display:inline; width:165px;overflow:hidden;word-break: break-all;word-wrap: break-word;}
#c .block{ width:0; height:10px; background:#9C9C9B;}
#c a{color:#2D5169; position:absolute; right:5px; top:0;}
</style>
<body>
<div id="c">
</div>
<script language="javascript" type="text/javascript">
(function(doc){
var window = this;
var _extend = function(obj,o){
for(var name in o){
obj[name] = o[name];
}
}
var _$q = function(name,p){
return p.getElementsByTagName(name);
}
var _$c = function(name,p){
var elem = doc.createElement(name);
p&&p.appendChild(elem);
return elem;
}
window.upload = {
options : {
maxSize : 35, //35m的意思
message : "文件不能超过{size}m"
},
init : function(options){
_extend(this.options,options);
_extend(this,this.options);
if(!this.elem || !this.elem.nodeName){
return;
}
var t = new Date().getTime();
var ie = doc.all,
self = this;
if(ie){
this.elem.innerHTML = [
"<object id='flash_z' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='90' height='30'>",
"<param name='FlashVars' VALUE='' />",
"<param name='wmode' value='transparent'/>",
"<param name='Movie' value='upload.swf?"+t+"' />",
"<param name='Src' value='upload.swf?"+t+"' />",
"<param name='WMode' value='Window' />",
"<param name='Scale' value='NoScale' />",
"<param name='BGColor' value='#cccccc' />",
"<param name='AllowNetworking' value='all' />",
"<param name='AllowFullScreen' value='true' />",
"<param name='AllowScriptAccess' value='always' />",
"</object><div class='bar'></div>"
].join("");
this.flash = this.elem.childNodes[0];
this.bar = this.elem.childNodes[1];
this.flash.style.display = "none";
this.flashComplete = function(){
this.flash.style.display = "block";
this.flash.init(this.url+"_____"+this.maxSize);
}
}else{
this.elem.innerHTML = '<div class="btn">\
<form enctype="multipart/form-data" method="post" action="'+this.url+'">\
<input class="file" type="file" name="fileToUpload">\
</form>\
</div><div class="bar"></div>';
this.bar = this.elem.childNodes[1];
this.form = _$q("form",this.elem)[0];
this.input = _$q("input",this.elem)[0];
this.input.onchange = function(){
self.fileSelected();
}
this.createXhr();
}
this.bar.onclick = function(e){
var e = window.event || e,
elem = e.target || e.srcElement,
dom = elem.getAttribute("dom");
if(dom == "abort"){
ie
? self.flash.abort()
: self.xhr.abort();
}
}
},
creatBar : function(){
var list = this.list = _$c("div",this.bar);
list.className = "list";
list.innerHTML="<div class='loadbar'><div class='block'></div></div><span class='bai'></span><span class='info'></span><a dom='abort' href='javascript:;'>取消</a>"
this.block = _$q("div",list)[1];
this.a = _$q("a",list)[0];
var spans = _$q("span",list);
this.baiSpan = spans[0];
this.fileNameSpan = spans[1];
},
createXhr : function(){
var xhr = this.xhr = new XMLHttpRequest(),
self = this;
xhr.upload.addEventListener("progress", function(e){
if(e.lengthComputable){
var num = parseInt(((e.loaded)/(e.total))*10000)/10000;
num = num.toFixed(2);
self.progress(Math.min(0.99,num));
}
}, false);
xhr.addEventListener("load", function(){
//self.progress(1); //让进度条变满 上传完成时候的回调函数
}, false);
xhr.addEventListener("error", function(){
self.fail("上传失败");
}, false);
xhr.addEventListener("abort", function(){
self.abort();
}, false);
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if((xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 ){
try {
var o = eval("("+xhr.responseText+")");
if(o.valid == 1){
self.complete();
}else{
self.fail("上传失败了")
}
} catch (e) {
self.fail("上传失败");
}
}
}
}
},
abort : function(){
this.list.parentNode.removeChild(this.list);
_$q("div",this.bar).length ==0
&&(this.bar.style.display = "none");
},
complete : function(){
this.progress(1);
this.a.parentNode.removeChild(this.a);
this.a = null;
},
fileSelected : function(){
var fileInfo = this.input.files[0];
this.name = fileInfo.name;
this.size = fileInfo.size;
if(fileInfo.size>this.maxSize*1024*1024){
this.fail();
return;
}
this.selectHander();
this.uploadFile();
},
uploadFile : function(){
this.xhr.open("POST", this.url);
fd = new FormData(this.form)
fd.append("Filedata", this.input.files[0]);
this.xhr.send(fd);
},
fail : function(err){
alert(err||this.message.replace("{size}",this.maxSize));
_$q("div",this.bar).length ==0
&&(this.bar.style.display = "none");
},
progress : function(val){
val =100*val+"";
if(val.length>5){
val.indexOf(".")>0
? val = val.substr(0,5)
: val = val.substr(0,2);
}
this.block.style.width = val+"px";
this.baiSpan.innerHTML = val+"%";
},
log: function(s){
//alert(s) 调试flash用的
},
selectHander : function(){
this.creatBar();
this.fileNameSpan.innerHTML = this.name+"("+this.howSize(this.size)+")";
this.bar.style.display = "block";
},
setValue : function(obj){
obj = eval("("+obj+")");
_extend(upload,obj);
upload.selectHander();
},
howSize : function(size){
if(size<1024){
return size+"kb";
}else if(size<1024*1024){
return (size/1024).toFixed(2) + "k";
}else{
return (size/(1024*1024)).toFixed(2) + "m";
}
}
}
})(document);
upload.init({
elem : document.getElementById("c"),
url : "upload.php",
maxSize : 30
});
</script>
</body>
</html>