JQUERY+ASP.NET的AJAX檔案上傳(含Demo)

來源:互聯網
上載者:User

在知道JQUREY和微軟整合的訊息後,在項目裡面就開始盡量使用JQUERY了,這個DEMO是一個樣本。主要檔案兩個(另外我還打包了一些漂亮的AJAX處理等待的小圖片):

ajaxUpFile.ashx     服務端處理

Default.aspx     使用者提交

下面貼出主要代碼:

JS部分代碼如下

Code
    function TestUp()
    {
        ajaxFileUpload("FileUpload1");
    }
   
    function ajaxFileUpload(obfile_id)
    {
    //準備提交處理
    $("#loading_msg").html("<img src=/images/DotAjax.gif />");
   
    //開始提交
    $.ajax
    ({
        type: "POST",
        url:"ajaxUpFile.ashx",
        data:"upfile="+$("#"+obfile_id).val(),
        success:function (data, status)
        {           
            //alert(data);
            var stringArray = data.split("|");
            if(stringArray[0]=="1")
            {
                //stringArray[0]    成功狀態(1為成功,0為失敗)
                //stringArray[1]    上傳成功的檔案名稱
                //stringArray[2]    訊息提示
                $("#divmsg").html("<img src=/images/note_ok.gif />"+stringArray[2]+"  檔案地址:"+stringArray[1]);
                $("#filepreview").attr({ src:stringArray[1]});
            }           
            else
            {
                //上傳出錯
                $("#divmsg").html("<img src=/images/note_error.gif />"+stringArray[2]+"");
            }
                      
            $("#loading_msg").html("");
         },
        error:function (data, status, e)
        {
            alert("上傳失敗:"+e.toString());
        }
     });
     return false;//.NET按鈕控制項取消提交
}

C#代碼部分:

Code
        /// <summary>
        /// 上傳檔案 方法
        /// </summary>
        /// <param name="fileNamePath"></param>
        /// <param name="toFilePath"></param>
        /// <returns>返回上傳處理結果   格式說明: 0|file.jpg|msg   成功狀態|檔案名稱|訊息    </returns>
        public string UpLoadFile(string fileNamePath, string toFilePath)
        {
            try
            {
                //擷取要儲存的檔案資訊
                FileInfo file = new FileInfo(fileNamePath);
                //獲得副檔名
                string fileNameExt = file.Extension;

                //驗證合法的檔案
                if (CheckFileExt(fileNameExt))
                {
                    //產生將要儲存的隨機檔案名稱
                    string fileName = GetFileName() + fileNameExt;
                    //檢查儲存的路徑 是否有/結尾
                    if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";

                    //按日期歸類儲存
                    string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
                    if (true)
                    {
                        toFilePath += datePath;
                    }

                    //獲得要儲存的檔案路徑
                    string serverFileName = toFilePath + fileName;
                    //物理完整路徑                   
                    string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
                   
                    //檢查是否有該路徑  沒有就建立
                    if (!Directory.Exists(toFileFullPath))
                    {
                        Directory.CreateDirectory(toFileFullPath);
                    }

                    //將要儲存的完整檔案名稱               
                    string toFile = toFileFullPath + fileName;

                    ///建立WebClient執行個體      
                    WebClient myWebClient = new WebClient();
                    //設定windows網路安全認證   方法1
                    myWebClient.Credentials = CredentialCache.DefaultCredentials;
                    ////設定windows網路安全認證   方法2
                    //NetworkCredential cred = new NetworkCredential("UserName", "UserPWD");
                    //CredentialCache cache = new CredentialCache();
                    //cache.Add(new Uri("UploadPath"), "Basic", cred);
                    //myWebClient.Credentials = cache;

                    //要上傳的檔案      
                    FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                    //FileStream fs = OpenFile();      
                    BinaryReader r = new BinaryReader(fs);
                    //使用UploadFile方法可以用下面的格式      
                    //myWebClient.UploadFile(toFile, "PUT",fileNamePath);      
                    byte[] postArray = r.ReadBytes((int)fs.Length);
                    Stream postStream = myWebClient.OpenWrite(toFile, "PUT");
                    if (postStream.CanWrite)
                    {
                        postStream.Write(postArray, 0, postArray.Length);
                    }
                    else
                    {
                        return "0|" + serverFileName + "|" + "檔案目前不可寫";
                    }
                    postStream.Close();

                    return "1|" + serverFileName + "|" + "檔案上傳成功";
                }
                else
                {
                    return "0|errorfile|" + "檔案格式非法";
                }
            }
            catch (Exception e)
            {
                return "0|errorfile|" + "檔案上傳失敗,錯誤原因:" + e.Message;
            }
        }

DEMO:點擊下載!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.