異步上傳文件解決方法



一、

通過iframe來實現無刷新的的文件上傳,其實是有刷新的,只是在iframe裏面隱藏了而已

簡單的原理說明:

<form id="form1" method="post" action="upload.do" enctype="multipart/form-data"  target="uploadframe" >
<input type="file" id="upload" name="文件上傳" />
</form>

<iframe id="uploadframe" name="result_frame"   style="visibility:hidden;"></iframe>

 

form裏面的target要與iframe裏面的id的值相等,指示是form相應了post事件,也就是post時間相應的時候刷新的是iframe而不是整個頁面。

 

二、

利用jQuery的插件AjaxFileUpload 可以簡單地實現這個異步的上傳的效果      插件地址: http://www.phpletter.com/Our-Projects/AjaxFileUpload/

 

 <script type="text/javascript" language="javascript" src="js/jquery.js"></script>

 <script type="text/javascript" language="javascript" src="js/ajaxfileupload.js"></script>

 

代碼

    function ajaxFileUpload()
    {
        $("#loading")
        .ajaxStart(function(){
            $(this).show();            
        })
        .ajaxComplete(function(){
            $(this).hide();            
        });

        $.ajaxFileUpload
        (
            {
                url:'Upload.ashx',
                secureuri:false,
                fileElementId:'fileToUpload',
                dataType: 'json',
                success: function (data, status)
                {                
                    if(typeof(data.error) != 'undefined')
                    {
                        if(data.error != '')
                        {
                            alert(data.error);
                        }else
                        {
                            alert(data.msg);
                        }
                    }
                },
                error: function (data, status, e)
                {
                    alert(e);
                }
            }
        )
        
        return false;

    }

<input id="fileToUpload" type="file" size="45" name="fileToUpload">

<input type="button" id="buttonUpload" οnclick="return ajaxFileUpload();">
       上傳</input>

 

 

Upload.ashx


代碼

if (Request.Files.Count > 0)
   {
    HttpPostedFile file = Request.Files[0];
    string msg = "";
    string error = "";
    if (file.ContentLength == 0)
     error = "文件長度爲0";
    else
    {
     file.SaveAs(Server.MapPath("file") + "\\" + Path.GetFileName(file.FileName));
     msg = "上傳成功";
    }
    string result = "{ error:'" + error + "', msg:'" + msg + "'}";
    Response.Write(result);
    Response.End();
   }


PS:ajaxfileupload.js代碼


代碼

jQuery.extend({

    createUploadIframe: function(id, uri)
    {
            //create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                }
                else if(typeof uri== 'string'){
                    io.src = uri;
                }
            }
            else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io            
    },
    createUploadForm: function(id, fileElementId)
    {
        //create form    
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');    
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        //set attributes
        $(form).css('position', 'absolute');
        $(form).css('top', '-1200px');
        $(form).css('left', '-1200px');
        $(form).appendTo('body');        
        return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout        
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
        var form = jQuery.createUploadForm(id, s.fileElementId);
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;        
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
        {
            jQuery.event.trigger( "ajaxStart" );
        }            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
        {            
            var io = document.getElementById(frameId);
            try 
            {                
                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;
                     
                }else 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;
                }                        
            }catch(e)
            {
                jQuery.handleError(s, xml, null, e);
            }
            if ( xml || isTimeout == "timeout") 
            {                
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
                    {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
                {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
                                    {    try 
                                        {
                                            $(io).remove();
                                            $(form).remove();    
                                            
                                        } catch(e) 
                                        {
                                            jQuery.handleError(s, xml, null, e);
                                        }                                    

                                    }, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
        {
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
        {
           // var io = $('#' + frameId);
            var form = $('#' + formId);
            $(form).attr('action', s.url);
            $(form).attr('method', 'POST');
            $(form).attr('target', frameId);
            if(form.encoding)
            {
                form.encoding = 'multipart/form-data';                
            }
            else
            {                
                form.enctype = 'multipart/form-data';
            }            
            $(form).submit();

        } catch(e) 
        {            
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }         
        return {abort: function () {}};    

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
            //alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})


三、純iframe實現上傳

upload.ashx

代碼

//<%@ WebHandler Language="C#" Class="upload" %>

using System;
using System.Web;

public class upload : IHttpHandler {
    private string Js(string v) {//此函數進行js的轉義替換的,防止字符串中輸入了'後造成回調輸出的js中字符串不閉合
        if (v == null) return "";
        return v.Replace("'", @"\'");
    }
    //下面就是一個簡單的示例,保存上傳的文件,如果要驗證上傳的後綴名,得自己寫,還有寫數據庫什麼的
    public void ProcessRequest (HttpContext context) {
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;
        HttpServerUtility Server = context.Server;
        //指定輸出頭和編碼
        Response.ContentType = "text/html";
        Response.Charset = "utf-8";
        
        HttpPostedFile f = Request.Files["upfile"];//獲取上傳的文件
        string des = Request.Form["des"]//獲取描述
            ,newFileName=Guid.NewGuid().ToString();//使用guid生成新文件名

        if (f.FileName == "")//未上傳文件
            Response.Write("<script>parent.UpdateMsg('','');</script>");//輸出js,使用parent對象得到父頁的引用
        else { //保存文件
            newFileName += System.IO.Path.GetExtension(f.FileName);//注意加上擴展名
            try {
                f.SaveAs(Server.MapPath("~/uploads/" + newFileName));//如果要保存到其他地方,注意修改這裏

                //調用父過程更新內容,注意要對des變量進行js轉義替換,防止字符串不閉合提示錯誤
                Response.Write("<script>parent.UpdateMsg('" +Js(des)+ "','" + newFileName + "')</script>");
            }
            catch {
                Response.Write("<script>alert('保存文件失敗!\\n請檢查文件夾是否有寫入權限!');</script>");//如果保存失敗,輸出js提示保存失敗
            }
            
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


test.htm


代碼

<!!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>使用隱藏的Iframe實現ajax無刷新上傳</title>
</head>
<body>
    <script type="text/javascript">
    function UpdateMsg(des,filename){//此函數用來提供給提交到的頁面如upload.ashx輸出js的回調,更新當前頁面的信息
      if(filename==''){alert('未上傳文件!');return false;}
      document.getElementById('ajaxMsg').innerHTML='你在表單中輸入的“文件描述”爲:'+des+'<br/>'
      +'上傳的圖片爲:<a href="uploads/'+filename+'" target="_blank">'+filename+'</a>';
    }
    
    function check(f){
      if(f.des.value==''){
         alert('請輸入文件描述!');f.des.focus();return false;
      }
      if(f.upfile.value==''){
        alert('請選擇文件!');f.upfile.focus();return false;
      }
    }
    </script> 
    <!--隱藏的iframe來接受表單提交的信息-->
    <iframe name="ajaxifr" style="display:none;"></iframe>
    <!--這裏設置target="ajaxifr",這樣表單就提交到iframe裏面了,和平時未設置target屬性時默認提交到當前頁面-->
    <!--注意一點的是使用iframe時在提交到的頁面可以直接輸出js來操作父頁面的信息,一般的ajax提交文本信息時你需要返回信息,如果是js信息你還得eval下-->
    <form method="post" enctype="multipart/form-data" action="upload.ashx" target="ajaxifr" οnsubmit="return check(this)">
    文件描述:<input type="text" name="des" /><br >
    選擇文件:<input type="file" name="upfile" /><br >
    <input type="submit" value="提交" />
    </form>
    <!--放入此div用來實現上傳的結果-->
    <div id="ajaxMsg"></div>
</body>
</html>




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章