这两款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
- // $_files['photofile']:是获得上传图片的数组
- // $uploadfile:存放地址
- $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;
- }
- /*file容器样式*/
- 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;
- }
- /*file设为透明,并覆盖整个触发面*/
- a.files input {
- margin-left:-350px;
- font-size:30px;
- cursor:pointer;
- filter:alpha(opacity=0);
- opacity:0;
- }
- /*取消点击时的虚线框*/
- a.files, a.files input {
- outline:none;/*ff*/
- hide-focus:expression(this.hidefocus=true);/*ie*/
- }
- </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){
- //为每个实例创建不同的iframe
- this._framename = "uploadframe_" + math.floor(math.random() * 1000);
- //ie不能修改iframe的name
- var oframe = isie ? document.createelement("<iframe name="" + this._framename + "">") : document.createelement("iframe");
- //为ff设置name
- oframe.name = this._framename;
- oframe.style.display = "none";
- //在ie文档未加载完用appendchild会报错
- document.body.insertbefore(oframe, document.body.childnodes[0]);
- }//开源代码Vevb.com
- //设置form属性,关键是target要指向iframe
- this.form.target = this._framename;
- this.form.method = "post";
- //注意ie的form没有enctype属性,要用encoding
- this.form.encoding = "multipart/form-data";
- //整理一次
- this.ini();
- },
- //设置默认属性
- setoptions: function(options) {
- this.options = {//默认值
- filename: "files[]",//文件上传控件的name,配合后台使用
- framename: "",//iframe的name,要自定义iframe的话这里设置name
- oninifile: function(){},//整理文件时执行(其中参数是file对象)
- onempty: function(){},//文件空值时执行
- limit: 10,//文件数限制,0为不限制
- onlimite: function(){},//超过文件数限制时执行
- distinct: true,//是否不允许相同文件
- onsame: function(){},//有相同文件时执行
- extin: ["gif","jpg","rar","zip","iso","swf","exe"],//允许后缀名
- onnotextin: function(){},//不是允许后缀名时执行
- extout: [],//禁止后缀名,当设置了extin则extout无效
- onextout: function(){},//是禁止后缀名时执行
- onfail: function(){},//文件不通过检测时执行(其中参数是file对象)
- onini: function(){}//重置时执行
- };
- extend(this.options, options || {});
- },
- //整理空间
- ini: function() {
- //整理文件集合
- this.files = [];
- //整理文件空间,把有值的file放入文件集合
- each(this.folder.getelementsbytagname("input"), bind(this, function(o){
- if(o.type == "file"){ o.value && this.files.push(o); this.oninifile(o); }
- }))
- //插入一个新的file
- 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();
- },
- //检测file对象
- 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);
- },
- //删除指定file
- delete: function(file) {
- //移除指定file
- this.folder.removechild(file); this.ini();
- },
- //删除全部file
- 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);
- })
- //ie的table不支持innerhtml所以这样清空table
- while(filelist.haschildnodes()){ filelist.removechild(filelist.firstchild); }
- filelist.appendchild(ofragment);
- }
- $("idlimit").innerhtml = fu.limit;
- $("idext").innerhtml = fu.extin.join(",");
- $("idbtndel").onclick = function(){ fu.clear(); }
- //在后台通过window.parent来访问主页面的函数
- 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;//是否允许覆盖相同文件,1:允许,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>
新闻热点
疑难解答