搜索
首页php教程php手册PHP Ajax上传文件实例[ajaxfileupload.js]

PHP Ajax上传文件实例[ajaxfileupload.js]

Jun 13, 2016 am 09:49 AM
ajaxjqueryphp上传使用实例文件

讲过利用jquery ajax与php实现图片上传,下面我介绍利用php ajax实现各种文件无刷新上传,直接放实例希望给各位同学有帮助。

可以批量进行添加上传,简单方便

 代码如下 复制代码
 


 


jQuery.extend({
   
 

    createUploadIframe: function(id, uri)
    {
           //create frame
            var frameId = 'jUploadFrame' id;
            var iframeHtml = '            if(window.ActiveXObject)
           {
                if(typeof uri== 'boolean'){
                  iframeHtml = ' src="' 'javascript:false' '"';
 

                }
                else if(typeof uri== 'string'){
                  iframeHtml = ' src="' uri '"';
 

                }
           }
           iframeHtml = ' />';
           jQuery(iframeHtml).appendTo(document.body);
 

            return jQuery('#' frameId).get(0);       
    },
    createUploadForm: function(id, fileElementId, data)
    {
       //create form
       var formId = 'jUploadForm' id;
       var fileId = 'jUploadFile' id;
       var form = jQuery('

');  
       if(data)
       {
           for(var i in data)
           {
              jQuery('').appendTo(form);
           }         
       }     
       var oldElement = jQuery('#' fileElementId);
       var newElement = jQuery(oldElement).clone();
       jQuery(oldElement).attr('id', fileId);
       jQuery(oldElement).before(newElement);
       jQuery(oldElement).appendTo(form);
 

 

      
       //设置属性
       jQuery(form).css('位置', '绝对');
       jQuery(form).css('top', '-1200px');
       jQuery(form).css('left', '-1200px');
       jQuery(form).appendTo('body');    
       退货表格;
    },
 

    ajaxFileUpload:函数 {
        // TODO 引入全局设置,允许客户端修改所有请求,而不仅仅是超时     
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()       
       var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
       var io = jQuery.createUploadIframe(id, s.secureuri);
       var frameId = 'jUploadFrame' id;
       var formId = 'jUploadForm' id;      
        // 观察一组新的请求
        if ( s.global && !jQuery.active )
       {
           jQuery.event.trigger( "ajaxStart" );
       }           
        var requestDone = false;
        // 创建请求对象
        var xml = {}  
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // 等待响应返回
        var uploadCallback = function(isTimeout)
       {         
           var io = document.getElementById(frameId);
            尝试
           {            
              if(io.contentWindow)
              {
                   xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                   xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
                  
              }否则 if(io.contentDocument)
              {
                   xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                  xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
              }                   
            }抓住(e)
           {
              jQuery.handleError(s, xml, null, e);
           }
            if ( xml || isTimeout == "超时")
           {            
                requestDone = true;
                var 状态;
                尝试{
                    状态= isTimeout!=“超时”? "成功" : "错误";
                    // 确保请求成功或未修改
                    if ( 状态 != "错误" )
                  {
                        // 处理数据(无论回调如何,都通过 httpData 运行 xml)
                        var data = jQuery.uploadHttpData( xml, s.dataType );   
                        // 如果指定了本地回调,则触发它并向其传递数据
                        if ( s.成功 )
                            s.success( 数据, 状态 );
   
                        // 触发全局回调
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } 其他
                        jQuery.handleError(s, xml, status);
                } catch(e)
              {
                    状态=“错误”;
                    jQuery.handleError(s, xml, status, e);
                }
 

                // 请求已完成
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );
 

                // 处理全局 AJAX 计数器
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );
 

                // 处理结果
                if ( s.complete )
                    s.complete(xml, 状态);
 

                jQuery(io).unbind()
 

                setTimeout(function()
                                {   尝试
                                   {
                                       jQuery(io).remove();
                                       jQuery(表单).remove();  
                                      
                                   } catch(e)
                                   {
                                       jQuery.handleError(s, xml, null, e);
                                   }                             
 

                                }, 100)
 

                xml = null
 

            }
        }
        // 超时检查器
        if ( s.timeout > 0 )
       {
            setTimeout(function(){
                // 检查请求是否仍在发生
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        尝试
       {
 

           var form = jQuery('#' formId);
           jQuery(form).attr('action', s.url);
           jQuery(form).attr('方法', 'POST');
           jQuery(form).attr('target', frameId);
            if(form.encoding)
           {
              jQuery(form).attr('编码', '多部分/表单数据');              
            }
            其他
           {  
              jQuery(form).attr('enctype', 'multipart/form-data');       
            }       
            jQuery(form).submit();
 

        } catch(e)
       {         
            jQuery.handleError(s, xml, null, e);
        }
      
       jQuery('#'frameId).load(uploadCallback );
        返回{中止:函数(){}}; 
 

    },
 

    uploadHttpData: function( r, type ) {
        var data = !type;
        数据=类型==“xml”||数据 ? r.responseXML : r.responseText;
        // 如果类型是“script”,则在全局上下文中对其进行评估
        if ( type == "script" )
            jQuery.globalEval( 数据 );
        // 如果使用 JSON,则获取 JavaScript 对象。
        if ( type == "json" )
            eval( "data = " data );
        // 评估 html
中的脚本         if ( type == "html" )
            jQuery("

").html(data).evalScripts();
 

        返回数据;
    }
})

脚本>
 


   
       id=“文件1”大小=“30”/>        onclick =“返回ajaxFileUpload();” >>        style="display: none">正在上传...
表格>
 


var str = '';
函数 ajaxFileUpload(){ 
    $("#msg")
    .ajaxStart(function(){
       $(this).show();
    });
    /*
    .ajaxComplete(function(){
       $(this).hide();
    });
    */
    $.ajaxFileUpload(
    {
       url:'up_deal.php',
       secureuri:假,
       fileElementId:'file1',
       数据类型:'文本',
       //data:{name:'qinmi', id:'123'},
       成功:函数(数据){
              if(数据=='错误'){
                  $('#msg').html("上传失败");
              }其他{
                  $('#msg').html("上传成功");
                  str = 数据'@';
                  $('#fname').val(str);
              }
           }
       }
    );
    返回错误;
}
脚本>


 
up_deal.php

 代码如下
 代码如下 复制代码

if ((($_FILES["file1"]["type"] == "image/gif")
|| ($_FILES["file1"]["type"] == "image/jpeg")
|| ($_FILES["file1"]["type"] == "image/bmp")
|| ($_FILES["file1"]["type"] == "image/pjpeg"))
&& ($_FILES["file1"]["size"]     $extend = explode(".",$_FILES["file1"]["name"]);
    $key = count($extend)-1;
    $ext = ".".$extend[$key];
    $newfile = time().$ext;
 

    if(!file_exists('upload')){mkdir('upload');}
    move_uploaded_file($_FILES["file1"]["tmp_name"],"upload/" . $newfile);
    @unlink($_FILES['file1']);
    echo $newfile;
}else {
    echo 'error';
}
?>

复制代码 if ((($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/bmp") || ($_FILES["file1"]["type"] == "image/pjpeg")) && ($_FILES["file1"]["size"]     $extend = Explode(".",$_FILES["file1"]["name"]);     $key = count($extend)-1;     $ext = ".".$extend[$key];     $newfile = time().$ext;       if(!file_exists('upload')){mkdir('upload');}     move_uploaded_file($_FILES["file1"]["tmp_name"],"upload/" . $newfile);     @unlink($_FILES['file1']);     回显 $newfile; }否则{     echo '错误'; } ?>
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中