单页面多类型的多附件上传

JS的多附件上传在这就不详细描述了,网上有很多大家可以各自百度去;我在这要说的是单个页面——多个类型——多附件上传,怕描述不清附上图。

虽然这么做可能不是太好,但是客户确定的UI是这样,也就只能这么做了。

页面如上图所示,下面看看前台代码吧:

<!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">
    <script src="AddFile.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">
        //获取每一类型上传控件的个数
        function getfile() {
            var hfC1 = document.getElementById("hfC1");
            var hfC2 = document.getElementById("hfC2");
            var hfC3 = document.getElementById("hfC3");
            var C1 = document.getElementById("C1").getElementsByTagName("input");
            var C2 = document.getElementById("C2").getElementsByTagName("input");
            var C3 = document.getElementById("C3").getElementsByTagName("input");
            hfC1.value = C1.length / 2;
            hfC2.value = C2.length / 2;
            hfC3.value = C3.length / 2;
        }   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="background-color: white;">
        <table style="width: 90%; margin-left: auto; margin-right: auto;">
            <tr>
                <td>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td align="center">
                    <table cellpadding="1" cellspacing="1" style="width: 70%; background-color: Black">
                        <tr style="background-color: white">
                            <td width="30%">
                                资料C1
                            </td>
                            <td width="70%" align="left">
                                <div id="C1">
                                    <asp:FileUpload ID="fuC1" runat="server" onchange="if(this.value)judge(this.value,this);" />
                                    <asp:Button ID="btn_addC1" runat="server" class="buttonAdd" OnClientClick=" return addfile('C1')"
                                        Style="width: 60px; background-repeat: no-repeat;" Text="添加" />
                                </div>
                                <asp:HiddenField ID="hfC1" runat="server" Value="###" />
                            </td>
                        </tr>
                        <tr style="background-color: white">
                            <td>
                                资料C2
                            </td>
                            <td align="left">
                                <div id="C2">
                                    <asp:FileUpload ID="fuC2" runat="server" onchange="if(this.value)judge(this.value,this);" />
                                    <asp:Button ID="btn_addC2" runat="server" class="buttonAdd" OnClientClick=" return addfile('C2')"
                                        Style="width: 60px; background-repeat: no-repeat;" Text="添加" />
                                </div>
                                <asp:HiddenField ID="hfC2" runat="server" Value="###" />
                            </td>
                        </tr>
                        <tr style="background-color: white">
                            <td>
                                资料C3
                            </td>
                            <td align="left">
                                <div id="C3">
                                    <asp:FileUpload ID="fuC3" runat="server" onchange="if(this.value)judge(this.value,this);" />
                                    <asp:Button ID="btn_addC3" runat="server" class="buttonAdd" OnClientClick=" return addfile('C3')"
                                        Style="width: 60px; background-repeat: no-repeat;" Text="添加" />
                                </div>
                                <asp:HiddenField ID="hfC3" runat="server" Value="###" />
                            </td>
                        </tr>
                        <tr style="background-color: white">
                            <td colspan="2">
                                <asp:Button ID="btnsure" runat="server" Text="上传" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

judge()方法是用来判断上传文件的类型的,注意:每一类型下面都有一个隐藏控件的。

添加上传控件的JS方法可以提取放在JS文件里,代码如下:

//添加附件上传控件
function addfile(id) {
    var d = document.createElement("div");
    //添加上传控件
    var f = document.createElement("input");
    f.setAttribute("type", "file");
    f.setAttribute("name", "upfile");
    f.setAttribute("style", "margin-top:3px;margin-bottom:3px;");
    f.onchange = function () {
        if (this.value) judge(this.value, this);
    }
    d.appendChild(f);
    //添加删除按钮
    var b = document.createElement("input");
    b.setAttribute("type", "button");
    b.style.cssText = "width:45px;border:0;background-color:#f1f9fe;color:Blue;cursor:hand;";
    b.setAttribute("value", "[删除]");
    b.onclick = function () {
        return delfile(this);
    }
    d.appendChild(b);
    document.getElementById(id).appendChild(d);
    return false;
}
//公用删除
function delfile(f) {
    while (f.tagName != "DIV")
        f = f.parentNode;
    f.parentNode.removeChild(f);
    return false;
}
//判断doc和xls文件
function judge(file, node) {
    if (file) {
        var suffix = file.split(".");
        var num = suffix.length - 1;
        var name = suffix[num].toLowerCase();
        if (name != "doc" && name != "xls") {
            alert("上传类型错误,暂只支持.doc和.xls格式!");
            node.outerHTML = node.outerHTML;
        }
    }
}

至此前台结束,下面看后台代码吧:

 

protected void btnsure_Click(object sender, EventArgs e)
    {
        int bu = Convert.ToInt32(hfC1.Value.ToString());
        int care = Convert.ToInt32(hfC2.Value.ToString());
        int re = Convert.ToInt32(hfC3.Value.ToString());
        int upsize = 4000000;
        try
        {
            upsize = Convert.ToInt32(ConfigurationManager.AppSettings["upsize"].ToString());
        }
        catch (Exception) { }
        //存储C1
        FileAttaInfo attainfoC1 = upfile(0, bu, hfC1);
        if (attainfoC1 == null)
        {
            //刚才上传的文件删除
            delfile(hfC1.Value.ToString());
            //提示
            ShowMessages("上传失败,上传文件不能大于" + upsize / 1000000 + "M!");
            return;
        }
        //存储C2
        FileAttaInfo attainfoC2 = upfile(bu, care + bu, hfC2);
        if (attainfoC2 == null)
        {
            //刚才上传的文件删除
            delfile(hfC2.Value.ToString());
            //提示
            ShowMessages("上传失败,上传文件不能大于" + upsize / 1000000 + "M!");
            return;
        }
        //存储C3
        FileAttaInfo attainfoC3 = upfile(care + bu, re + care + bu, hfC3);
        if (attainfoC3 == null)
        {
            //刚才上传的文件删除
            delfile(hfC3.Value.ToString());
            //提示
            ShowMessages("上传失败,上传文件不能大于" + upsize / 1000000 + "M!");
            return;
        }
    }


    #region 上传文件
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="file">文件名</param>
    /// <param name="mark">标识</param>
    /// <returns></returns>
    public FileAttaInfo upfile(int start, int end, HiddenField hfcount)
    {
        int upsize = 4000000;
        try
        {
            upsize = Convert.ToInt32(ConfigurationManager.AppSettings["upsize"].ToString());
        }
        catch (Exception) { }

        //清空隐藏控件的值,用于存放路径,以便数据保存失败时删除文件
        if (hfcount != null)
        {
            hfcount.Value = "";
        }
        //设置文件夹的名称
string year = System.DateTime.Now.Year.ToString() + "";
        string month = System.DateTime.Now.Month.ToString() + "";
        string day = System.DateTime.Now.Day.ToString() + "";

        //设置上传路径
        string path = Server.MapPath("../UpFile/" + year + "/" + month + "/" + day + "/");
//判断上传文件夹是否存在,若不存在,则创建
        if (!Directory.Exists(path))
        {
            //创建文件夹
            Directory.CreateDirectory(path);
        }

        string attaname = "";

     string attaurl = "";

        FileAttaInfo attainfo = null;

//遍历页面中的上传控件 HttpFileCollection files = HttpContext.Current.Request.Files; for (int i = start; i < end; i++) { HttpPostedFile postedFile = files[i]; if (postedFile.FileName != "") { if (postedFile.ContentLength < upsize) {
           string[] name = postedFile.FileName.ToString().Split('\\');
               
string extname = System.IO.Path.GetExtension(postedFile.FileName);               
//获取上传文件的名称
               
string oglname = name[name.Length - 1].ToString().Replace(extname, "");

//存储上传的文件名       
attaname
+= oglname + ",";
               
//为上传的文件设置新的名称,防止重名
               
string newname = System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + i.ToString();
               
newname
= newname + extname ;

//设置完整的文件上传路径
               
string filepath = path + newname;
postedFile.SaveAs(filepath);
if (hfcount != null) { hfcount.Value += filepath + "$"; } int j = filepath.IndexOf("UpFile"); string str = filepath.Substring(j - 1); attaurl += "~" + str + ","; } else { return null; } } } attaname = attaname.TrimEnd(',');
           
attaurl = attaurl.TrimEnd(',');

if (attaname != "" && attaurl != "") { attainfo = new FileAttaInfo(attaname, attaurl); } else { attainfo = new FileAttaInfo(); } return attainfo; } #endregion #region 删除上传的文件 /// <summary> /// 删除文件 /// </summary> /// <param name="path">路径</param> public static void delfile(string path) { string[] upfile = path.Split('$'); for (int i = 0; i < upfile.Length; i++) { if (System.IO.File.Exists(upfile[i].ToString())) { System.IO.File.Delete(upfile[i].ToString()); } } } #endregion

FileAttaInfo为附件表的基类,用来存储附件名称和地址,这样C1,C2,C3各自的附件信息就能很好的区分,顺利的存入数据库。

posted @ 2012-12-05 17:11  冷香残  阅读(578)  评论(0编辑  收藏  举报