jquery+ajax 文件上傳功能(無ifram嵌套)

這兩天作項目(MVC3),不少地方都須要使用到文件上傳功能,可是採用的方式都是經過submit表單的方式來實現附件的上傳的,這樣感受每次都要刷新頁面很不爽,因此想來想去仍是準備寫一個通用的文件上傳功能來實現文件上傳。javascript

既然決定要作就立刻動手,此次我採用的方式是,jquery+ajax來實現文件的上傳,這裏須要使用一個別人寫的js插件:jquery-form.js,相關文檔資料地址:http://www.aqee.net/docs/jquery.form.plugin/jquery.form.plugin.html#apicss

經過使用上述插件,我能夠經過ajax來提交表單,而不會刷新頁面。主要使用的方法是 $("#myformID").ajaxSubmit()方法。html

好了廢話很少說,仍是上代碼:java

首先是展現頁面須要作的:分別引入jquery.js,jquery-form.js,還有fileload.jsjquery

如下是展現頁面代碼: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 runat="server">
    <title></title>
    <link href="CSS/Style.css" rel="Stylesheet" />
    <script type="text/javascript" src="jquery.js"></script>
    <script src="project/js/jquery.form.js" type="text/javascript"></script>
    <script src="project/js/fileload.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            createHtml($("#str"));
        })
    </script>
</head>
<body>
    <div id="str">
         
    </div>
</body>
</html>

下面是fileload.js代碼:api

function createHtml(obj) {
    var htmstr = [];
    htmstr.push(  "<form id='_fileForm' enctype='multipart/form-data'>");
    htmstr.push(  "<table cellspacing=\"0\" cellpadding=\"3\" style=\"margin:0 auto; margin-top:20px;\">");
    htmstr.push(  "<tr>");
    htmstr.push(  "<td class=\"tdt tdl\">請選擇文件:</td>");
    htmstr.push(  "<td class=\"tdt tdl\"><input id=\"loadcontrol\" type=\"file\" name=\"filepath\" id=\"filepath\" /></td>");
    htmstr.push(  "<td class=\"tdt tdl tdr\"><input type=\"button\" onclick=\"fileloadon()\" value=\"上傳\"/></td>");
    htmstr.push(  "</tr>");
    htmstr.push(  "<tr> <td class=\"tdt tdl tdr\" colspan='3'style='text-align:center;'><div id=\"msg\">&nbsp;</div></td> </tr>");
    htmstr.push(  "<tr> <td class=\"tdt tdl tdr\" style=\" vertical-align:middle;\">圖片預覽:</td> <td class=\"tdt tdl tdr\" colspan=\"2\"><div style=\"text-align:center;\"><img src=\"project/Images/NoPhoto.jpg\"/></div></td> </tr>");
    htmstr.push(  "</table>")
    htmstr.push(  "</form>");
    obj.html(htmstr.join(""));
}

function fileloadon() {
    $("#msg").html("");    
    $("img").attr({ "src": "project/Images/processing.gif" });
    $("#_fileForm").submit(function () {   
        $("#_fileForm").ajaxSubmit({
            type: "post",
            url: "project/help.aspx",
            success: function (data1) {
            var remsg = data1.split("|");
            var name = remsg[1].split("\/");
            if (remsg[0] == "1") {
            var type = name[4].substring(name[4].indexOf("."), name[4].length);
            $("#msg").html("文件名:" + name[name.length - 1] + "   ---  " + remsg[2]);
            switch (type) {
                case ".jpg":
                case ".jpeg":
                case ".gif":
                case ".bmp":
                case ".png":
                $("img").attr({ "src": remsg[1] });
                break;
            default:
                $("img").attr({ "src": "project/Images/msg_ok.png" });
                break;
            }
            } else {
                $("#msg").html("文件上傳失敗:" + remsg[2]);
                $("img").attr({ "src": "project/Images/msg_error.png" });
            }
            },
            error: function (msg) {
                alert("文件上傳失敗");    
            }
        });
        return false;
    });
    $("#_fileForm").submit();
}

在下面是服務頁面的代碼:服務器

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            HttpPostedFile postFile = Request.Files[0];
            //開始上傳
            string _savedFileResult = UpLoadFile(postFile);
            Response.Write(_savedFileResult);

        }
        catch(Exception ex)
        {
            Response.Write("0|error|上傳提交出錯");
        }

    }
    public string UpLoadFile(HttpPostedFile str)
    {
        return UpLoadFile(str, "/UpLoadFile/");
    }
    public string UpLoadFile(HttpPostedFile httpFile, string toFilePath)
    {
        try
        {
            //獲取要保存的文件信息
            string filerealname = httpFile.FileName;
            //得到文件擴展名
            string fileNameExt = System.IO.Path.GetExtension(filerealname);
            if (CheckFileExt(fileNameExt))
            {
                //檢查保存的路徑 是否有/結尾
                if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";

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

                //物理完整路徑                    
                string toFileFullPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + toFilePath;

                //檢查是否有該路徑  沒有就建立
                if (!System.IO.Directory.Exists(toFileFullPath))
                {
                    Directory.CreateDirectory(toFileFullPath);
                }

                //獲得服務器文件保存路徑
                string toFile = Server.MapPath("~" + toFilePath);
                string f_file = getName(filerealname);
                //將文件保存至服務器
                httpFile.SaveAs(toFile + f_file);
                return "1|" + toFilePath + f_file + "|" + "文件上傳成功";
            }
            else
            {
                return "0|errorfile|" + "文件不合法";
            }
        }
        catch (Exception e)
        {
            return "0|errorfile|" + "文件上傳失敗,錯誤緣由:" + e.Message;
        }
    }

    /// <summary>
    /// 獲取文件名
    /// </summary>
    /// <param name="fileNamePath"></param>
    /// <returns></returns>
    private string getName(string fileNamePath)
    {
        string[] name = fileNamePath.Split('\\');
        return name[name.Length - 1];
    }
    /// <summary>
    /// 檢查是否爲合法的上傳文件
    /// </summary>
    /// <param name="_fileExt"></param>
    /// <returns></returns>
    private bool CheckFileExt(string _fileExt)
    {
        string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".rar",".png" };
        for (int i = 0; i < allowExt.Length; i++)
        {
            if (allowExt[i] == _fileExt) { return true; }
        }
        return false;

    }

    public static string GetFileName()
    {
        Random rd = new Random();
        StringBuilder serial = new StringBuilder();
        serial.Append(DateTime.Now.ToString("HHmmss"));
        serial.Append(rd.Next(100, 999).ToString());
        return serial.ToString();

    }

代碼比較簡單,看官有疑問能夠評論,我會逐一回復。dom

運行defualt.aspx頁面之後顯示的效果是:post

上傳圖片則顯示對應的圖片:

 

 上傳壓縮文件(.rar)則顯示上傳成功圖片:

因爲服務端對文件類型有限制,若是須要支持更多類型的文件,請在服務端代碼中進行修改。

界面比較粗糙,看官見笑了...

附上源代碼(直接經過調試運行代碼,顯示不出圖片預覽,發佈出來之後就沒有問題):http://files.cnblogs.com/xlhblogs/ajax_FileUP.rar

轉自https://www.cnblogs.com/xlhblogs/archive/2012/07/05/2577116.html

相關文章
相關標籤/搜索