二款php ajax文件上传代码 |
时间:2015-01-23 来源:西部数据 作者:西部数据 |
|
这两款ajax文件上传代码其实都是利用了js的iframe或ajax post来实现的下面来看看代码吧,代码如下:
- <html>
- <body>
- <h1>ajax file upload sample</h1><br/><input id="uplaod" name="btn_send" type="button" value="上传测试"/>
- <div id=result></div>
- <pre class=js name="code">
- <script language="javascript">
- // 上传函数
- function btn_send.onclick() {
- data = ""
- spliter = "-------7d8d733180846"
- datadatadata = data + spliter + " "
- datadatadata = data + "content-disposition: form-data; name="photofile"; filename="c:\a.txt" "
- // datadatadata = data + "content-type: image/pjpeg" + vbcrlf
- datadatadata = data + "content-type: text/plain" + " " + " "
- text = "my name is wilson lin."
- postlength = text.length + data.length + 2 + spliter.length + 4
- package = data + text + " " + spliter + "-- "
-
- alert(package)
- // 把xml文档发送到web服务器
- var xmlhttp = new activexobject("microsoft.xmlhttp");
- xmlhttp.open("post","./upload.php",false);
- xmlhttp.setrequestheader("content-type", "multipart/form-data; boundary=-----7d8d733180846");
- xmlhttp.setrequestheader("content-length", postlength);
- xmlhttp.send(package);
- // 显示服务器返回的信息
- result.innerhtml=xmlhttp.responsetext;
- }
- </script>
- </pre>
- </body>
- </html>
-
-
- <html>
- <script language="javascript">
- <!--
- var xmlhttp;
- function createxmlhttprequest() {
- if (window.activexobject) {
- xmlhttp = new activexobject("microsoft.xmlhttp");
- }
- else if (window.xmlhttprequest) {
- xmlhttp = new xmlhttprequest();
- }
- }
- function uploade(e){
- var fileadd
- fileadd = e;
-
- createxmlhttprequest();
- xmlhttp.onreadystatechange = handlestatechange;
- var url = "pic_upload.asp教程?add="+fileadd+"×tamp="+new date().gettime();
- xmlhttp.open("get",url,true);
- xmlhttp.send(null);
-
- }
- function handlestatechange() {
- document.getelementbyid("content").innerhtml = "这里写进度条";
- if (xmlhttp.readystate == 4) {
- if (xmlhttp.status == 200) {
-
- document.getelementbyid("content").innerhtml = xmlhttp.responsetext;
-
- }
- else{
- //alert(xmlhttp.status);
- alert('错误,请联系管理员!');
-
- }
- }
- }
- //-->
- </script>
- <body>
- <input type=file name="mefile" id="fileadd" onchange="alert(document.getelementbyid('fileadd').value);">
- <input type="submit" value="上传" onclick="uploade(document.getelementbyid('fileadd').value);">
- <div id="content"></div>
- </body>
- </html>
upload.php文件,代码如下:
- <?php
-
-
- $uploadfile = "./".$_files['photofile']['name'];
- copy( $_files['photofile']['tmp_name'], $uploadfile );
- echo "url: <a href='http://localhost/".$_files['photofile']['name']."' target='_blank'>".$_files['photofile']['name']."</a><br/>";
- ?>
- upload successed!
实例代码二,代码如下:
- <!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=gb2312" />
- <title>无刷新文件上传系统</title>
- </head>
- <body>
- <style>
- .fu_list {
- width:600px;
- background:#ebebeb;
- font-size:12px;
- }
- .fu_list td {
- padding:5px;
- line-height:20px;
- background-color:#fff;
- }
- .fu_list table {
- width:100%;
- border:1px solid #ebebeb;
- }
- .fu_list thead td {
- background-color:#f4f4f4;
- }
- .fu_list b {
- font-size:14px;
- }
-
- a.files {
- width:90px;
- height:30px;
- overflow:hidden;
- display:block;
- border:1px solid #bebebe;
- background:url(img/fu_btn.gif) left top no-repeat;
- text-decoration:none;
- }
- a.files:hover {
- background-color:#ffffee;
- background-position:0 -30px;
- }
-
- a.files input {
- margin-left:-350px;
- font-size:30px;
- cursor:pointer;
- filter:alpha(opacity=0);
- opacity:0;
- }
-
- a.files, a.files input {
- outline:none;
- hide-focus:expression(this.hidefocus=true);
- }
- </style>
- <form id="uploadform" action="file.php">
- <table width="63%" border="0" cellspacing="1" class="fu_list">
- <thead>
- <tr>
- <td colspan="2"><b>上传文件</b></td>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td align="right" width="15%" style="line-height:35px;">添加文件:</td>
- <td><a href="javascript:void(0);" class="files" id="idfile"></a> <img id="idprocess" style="display:none;" src="img/loading.gif" /></td>
- </tr>
- <tr>
- <td colspan="2"><table border="0" cellspacing="0">
- <thead>
- <tr>
- <td>文件路径</td>
- <td width="100"></td>
- </tr>
- </thead>
- <tbody id="idfilelist">
- </tbody>
- </table></td>
- </tr>
- <tr>
- <td colspan="2" style="color:gray"><label for="textfield"></label>
- <input type="text" name="uploadsfile" id="uploadsfile" /></td>
- </tr>
- <tr>
- <td colspan="2" style="color:gray">温馨提示:最多可同时上传 <b id="idlimit"></b> 个文件,只允许上传 <b id="idext"></b> 文件。 </td>
- </tr>
- <tr>
- <td colspan="2" align="center" id="idmsg"><input type="button" value="开始上传" id="idbtnupload" disabled="disabled" />
-
- <input type="button" value="全部取消" id="idbtndel" disabled="disabled" />
- </td>
- </tr>
- </tbody>
- </table>
- </form>
- <script type="text/javascript">
-
- var isie = (document.all) ? true : false;
-
- var $ = function (id) {
- return "string" == typeof id ? document.getelementbyid(id) : id;
- };
-
- var class = {
- create: function() {
- return function() {
- this.initialize.apply(this, arguments);
- }
- }
- }
-
- var extend = function(destination, source) {
- for (var property in source) {
- destination[property] = source[property];
- }
- }
-
- var bind = function(object, fun) {
- return function() {
- return fun.apply(object, arguments);
- }
- }
-
- var each = function(list, fun){
- for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
- };
-
-
- var fileupload = class.create();
- fileupload.prototype = {
-
- initialize: function(form, folder, options) {
-
- this.form = $(form);
- this.folder = $(folder);
- this.files = [];
-
- this.setoptions(options);
-
- this.filename = this.options.filename;
- this._framename = this.options.framename;
- this.limit = this.options.limit;
- this.distinct = !!this.options.distinct;
- this.extin = this.options.extin;
- this.extout = this.options.extout;
-
- this.oninifile = this.options.oninifile;
- this.onempty = this.options.onempty;
- this.onnotextin = this.options.onnotextin;
- this.onextout = this.options.onextout;
- this.onlimite = this.options.onlimite;
- this.onsame = this.options.onsame;
- this.onfail = this.options.onfail;
- this.onini = this.options.onini;
-
- if(!this._framename){
-
- this._framename = "uploadframe_" + math.floor(math.random() * 1000);
-
- var oframe = isie ? document.createelement("<iframe name="" + this._framename + "">") : document.createelement("iframe");
-
- oframe.name = this._framename;
- oframe.style.display = "none";
-
- document.body.insertbefore(oframe, document.body.childnodes[0]);
- }
-
-
- this.form.target = this._framename;
- this.form.method = "post";
-
- this.form.encoding = "multipart/form-data";
-
-
- this.ini();
- },
-
- setoptions: function(options) {
- this.options = {
- filename: "files[]",
- framename: "",
- oninifile: function(){},
- onempty: function(){},
- limit: 10,
- onlimite: function(){},
- distinct: true,
- onsame: function(){},
- extin: ["gif","jpg","rar","zip","iso","swf","exe"],
- onnotextin: function(){},
- extout: [],
- onextout: function(){},
- onfail: function(){},
- onini: function(){}
- };
- extend(this.options, options || {});
- },
-
- ini: function() {
-
- this.files = [];
-
- each(this.folder.getelementsbytagname("input"), bind(this, function(o){
- if(o.type == "file"){ o.value && this.files.push(o); this.oninifile(o); }
- }))
-
- var file = document.createelement("input");
- file.name = this.filename; file.type = "file"; file.onchange = bind(this, function(){ this.check(file); this.ini(); });
- this.folder.appendchild(file);
-
- this.onini();
- },
-
- check: function(file) {
-
- var bcheck = true;
-
- if(!file.value){
- bcheck = false; this.onempty();
- } else if(this.limit && this.files.length >= this.limit){
- bcheck = false; this.onlimite();
- } else if(!!this.extin.length && !regexp(".(" + this.extin.join("|") + ")$", "i").test(file.value)){
-
- bcheck = false; this.onnotextin();
- } else if(!!this.extout.length && regexp(".(" + this.extout.join("|") + ")$", "i").test(file.value)) {
-
- bcheck = false; this.onextout();
- } else if(!!this.distinct) {
- each(this.files, function(o){ if(o.value == file.value){ bcheck = false; } })
- if(!bcheck){ this.onsame(); }
- }
-
- !bcheck && this.onfail(file);
- },
-
- delete: function(file) {
-
- this.folder.removechild(file); this.ini();
- },
-
- clear: function() {
-
- each(this.files, bind(this, function(o){ this.folder.removechild(o); })); this.ini();
- }
- }
-
- var fu = new fileupload("uploadform", "idfile", { extin: ["gif","jpg"],
- oninifile: function(file){ file.value ? file.style.display = "none" : this.folder.removechild(file); },
- onempty: function(){ alert("请选择一个文件"); },
- onlimite: function(){ alert("超过上传限制"); },
- onsame: function(){ alert("已经有相同文件"); },
- onnotextin: function(){ alert("只允许上传" + this.extin.join(",") + "文件"); },
- onfail: function(file){ this.folder.removechild(file); },
- onini: function(){
-
- var arrrows = [];
- if(this.files.length){
- var othis = this;
- each(this.files, function(o){
- var a = document.createelement("a"); a.innerhtml = "取消"; a.href = "javascript:void(0);";
- a.onclick = function(){ othis.delete(o); return false; };
- arrrows.push([o.value, a]);
- });
- } else { arrrows.push(["<font color='gray'>没有添加文件</font>", " "]); }
- addlist(arrrows);
-
- $("idbtnupload").disabled = $("idbtndel").disabled = this.files.length <= 0;
- }
- });
-
- $("idbtnupload").onclick = function(){
-
- var arrrows = [];
- each(fu.files, function(o){ arrrows.push([o.value, " "]); });
- addlist(arrrows);
-
- fu.folder.style.display = "none";
- $("idprocess").style.display = "";
- $("idmsg").innerhtml = "正在添加文件到您的网盘中,请稍候……<br />有可能因为网络问题,出现程序长时间无响应,请点击"<a href='?'><font color='red'>取消</font></a>"重新上传文件";
-
- fu.form.submit();
- }
-
-
- function addlist(rows){
-
- var filelist = $("idfilelist"), ofragment = document.createdocumentfragment();
-
- each(rows, function(cells){
- var row = document.createelement("tr");
- each(cells, function(o){
- var cell = document.createelement("td");
- if(typeof o == "string"){ cell.innerhtml = o; }else{ cell.appendchild(o); }
- row.appendchild(cell);
- });
- ofragment.appendchild(row);
- })
-
- while(filelist.haschildnodes()){ filelist.removechild(filelist.firstchild); }
- filelist.appendchild(ofragment);
- }
-
-
- $("idlimit").innerhtml = fu.limit;
-
- $("idext").innerhtml = fu.extin.join(",");
-
- $("idbtndel").onclick = function(){ fu.clear(); }
-
-
- function finish(msg)
- {
- $('uploadsfile').value=msg;
- }
-
- </script>
- </body>
- </html>
php接ajax上传代码,代码如下:
- <!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=gb2312" />
- <title>无标题文档</title>
- </head>
- <body>
- <?
- $sort=12;
- $f_type=strtolower("swf,jpg,rar,zip,7z,iso,gif");
- $file_size_max=200*1024*1024;
- $overwrite = 0;
- $f_input="files";
- foreach($_files[$f_input]["error"] as $key => $error){
- $up_error="no";
- if ($error == upload_err_ok){
- $f_name=$_files[$f_input]['name'][$key];
-
- $uploadfile=$uploaddir.strtolower(basename($f_name));
-
- $tmp_type=substr(strrchr($f_name,"."),1);
- $tmp_type=strtolower($tmp_type);
- if(!stristr($f_type,$tmp_type)){
- echo "<script>alert('对不起,不能上传".$tmp_type."格式文件, ".$f_name." 文件上传失败!')</script>";
- $up_error="yes";
- }
-
- if ($_files[$f_input]['size'][$key]>$file_size_max) {
-
- echo "<script>alert('对不起,你上传的文件 ".$f_name." 容量为".round($_files[$f_input]
- ['size'][$key]/1024)."kb,大于规定的".($file_size_max/1024)."kb,上传失败!')</script>";
- $up_error="yes";
- }
-
- if (file_exists($uploadfile)&&!$overwrite){
- echo "<script>alert('对不起,文件 ".$f_name." 已经存在,上传失败!')</script>";
- $up_error="yes";
- }
- $string = 'abcdefghijklmnopgrstuvwxyz0123456789';
- $rand = '';
- for ($x=0;$x<12;$x++)
- $rand .= substr($string,mt_rand(0,strlen($string)-1),1);
- $t=date("ymdhis").substr($gettime[0],2,6).$rand;
- $attdir="./file/";
- if(!is_dir($attdir))
- { mkdir($attdir);}
- $uploadfile=$attdir.$t.".".$tmp_type;
- if(($up_error!="yes") and (move_uploaded_file($_files[$f_input]['tmp_name']
-
- [$key], $uploadfile))){
-
-
- $_msg=$_msg.$f_name.'上传成功 ';
-
-
- }
- else{
- $_msg=$_msg.$f_name.'上传失败 ';
- }
- }
-
- }
- echo "<script>window.parent.finish('".$_msg."');</script>";
- ?>
- </body>
- </html>
|
|
|
|