上传控件和多个文件

前台 :
   <table style="width:100%">
         <tr>
             <td style="width:15%">
                 类型名称:</td>
             <td>
                <asp:DropDownList ID="TypeDDL" runat="server" Width="100px">
                 </asp:DropDownList>
                 &nbsp; &nbsp; &nbsp;<asp:Label ID="Lb1" runat="server" Text="创建人 :"></asp:Label>
                 <asp:Label ID="WriteLb" runat="server" Text=""></asp:Label>
                 &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; &nbsp;
                 <asp:Label ID="Lb2" runat="server" Text="创建时间:"></asp:Label>
                 <asp:Label ID="CreateTimeLb" runat="server" Text=""></asp:Label>
                 </td>
          </tr>
       
          <tr>
              <td>
                  文档标题:</td>
              <td>
                  <asp:TextBox ID="titleTB" runat="server" Width="300px"></asp:TextBox></td>
          </tr>
          <tr>
              <td>
                  文档内容:</td>
              <td>
                  <asp:TextBox ID="ContentTB" runat="server" TextMode="multiLine" Rows="20" Columns="80"></asp:TextBox></td>
          </tr>
         
         <tr>
             <td>
                 附件上传:</td>
             <td>
                 <input id="FindFile" runat="server" style="width: 370px" type="file" />&nbsp;
                
                 <asp:Button ID="addBt" runat="server" Text="上 传" OnClick="addBt_Click" /></td>  
             </tr>
           <tr>
             <td>
             </td>
             <td>
                <asp:DataList ID="viewAttachDL" runat="server" RepeatDirection="Horizontal" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" GridLines="Both" OnItemCommand="viewAttachDL_ItemCommand">
                     <ItemTemplate>
                         <table>
                             <tr>
                               <td align="left"><asp:Label ID="AttachViewLb" runat="server" Text='<%#Eval("fileName") %>'></asp:Label>
                               </td>
                              
                             </tr>
                             <tr>
                                <td align="center">
                                     <asp:ImageButton ID="attachImgBt" CommandName="attachImgBt" runat="server" ImageUrl="~/images/icon-delete.gif" CommandArgument='<%#Eval("fileid") %>'/>
                                 </td>
                             </tr>
                         </table>
                     </ItemTemplate>
                    <FooterStyle BackColor="#CCCCCC" />
                    <SelectedItemStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                    <ItemStyle BackColor="White" />
                    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                 </asp:DataList>
                  <asp:Label ID="labDetial" runat="server" Text=""></asp:Label>
                 <asp:Label ID="Document_AttachStatusLb" runat="server" Text=""></asp:Label>
                 <asp:Label ID="FileLb" runat="server" Text=""></asp:Label></td>
          </tr>
          <tr>
             <td>
             </td>
             <td>
               
                 <asp:Button ID="saveBt" runat="server" Text="保 存" OnClick="saveBt_Click" />
                  &nbsp; <asp:Button ID="returnBt" runat="server" Text="返 回" OnClick="returnBt_Click" />
                <asp:Label ID="labState" runat="server" Text=""></asp:Label></td>
          </tr>
           <tr>
             <td>
             </td>
             <td>
                </td>
          </tr>
        </table>
后台  :
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
    public partial class Document_Add : System.Web.UI.Page
    {
        SQLDataAccess SQLda = new SQLDataAccess();
        DataTable dt = new DataTable();
        Function fc = new Function();
        string TypeID = "-1";
        ArrayList files = new ArrayList();
        static ArrayList hif = new ArrayList();
        int filesUploaded = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                files.Clear();
                if (Request.Params["TypeID"] != null)
                {
                    TypeID = Request.Params["TypeID"].ToString();
                    ViewState["TypeID"] = TypeID;
                    GetRequest();
                    BindTypeDDL(TypeID);
                }
                else
                {
                    this.Lb1.Visible = false;
                    this.Lb2.Visible = false;
                    this.WriteLb.Visible = false;
                    this.CreateTimeLb.Visible = false;
                    BindTypeDDL();
                }
            }
        }
        protected void BindTypeDDL()
        {
            string strCmd = "SELECT * FROM CompanyDocumentType";
            dt = SQLda.GetTable(strCmd);
            this.TypeDDL.DataSource = dt;
            this.TypeDDL.DataValueField = "TypeID";
            this.TypeDDL.DataTextField = "TypeName";
            this.TypeDDL.DataBind();
        }
        protected void BindTypeDDL(string typeid)
        {
            string strCmd = "SELECT * FROM CompanyDocumentType WHERE TypeID=" + typeid;
            dt = SQLda.GetTable(strCmd);
            this.TypeDDL.DataSource = dt;
            this.TypeDDL.DataValueField = "TypeID";
            this.TypeDDL.DataTextField = "TypeName";
            this.TypeDDL.DataBind();
        }
        protected void GetRequest()
        {
            if (ViewState["TypeID"] != null)
            {
                TypeID = ViewState["TypeID"].ToString();
            }
            if (TypeID != "-1")
            {
                string strTxt = "SELECT * FROM CompanyDocumentType INNER JOIN xt_User ON CompanyDocumentType.WriteID=xt_User.UserID WHERE TypeID=" + TypeID;
                dt = SQLda.GetTable(strTxt);
                if (dt.Rows.Count != 0)
                {
                    this.WriteLb.Text = dt.Rows[0]["UserName"].ToString();
                    this.CreateTimeLb.Text = fc.GetFormatTime(dt.Rows[0]["CreateTime"].ToString());
                }
                //string strCmd = "SELECT * FROM CompanyDocument INNER JOIN CompanyDocumentType ON CompanyDocument.TypeID=CompanyDocumentType.TypeID INNER JOIN xt_User ON xt_User.UserID=CompanyDocument.WriteID WHERE CompanyDocument.TypeID=" + TypeID;
                //dt = SQLda.GetTable(strCmd);
            }
        }
        protected void Binddatalist(DataTable DatalistDT)
        {
            if (DatalistDT.Rows.Count != 0)
            {
    
                this.viewAttachDL.DataSource = DatalistDT;
                this.viewAttachDL.DataBind();
                this.viewAttachDL.Visible = true;
            }
            else
            {
                this.viewAttachDL.Visible = false;
            }
        }
        protected void addBt_Click(object sender, EventArgs e)
        {
            string Path = "../Company/空类型/", TypeName = "空类型";
            this.FileLb.Text = "";
            Document_AttachStatusLb.Text = "";
            this.labDetial.Text = "";
          
            if (ViewState["Path_Type_File"] == null)
            {
                string strCmd = "SELECT * FROM CompanyDocumentType WHERE TypeID=" + this.TypeDDL.SelectedValue;
                dt = SQLda.GetTable(strCmd);
                if (dt.Rows.Count != 0)
                {
                    TypeName = dt.Rows[0]["TypeName"].ToString();
                }
                DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("../Company/" + TypeName + "/"));
                Path = Server.MapPath("../Company/" + TypeName + "/");
                ViewState["Path"] = Path;
                if (!dirInfo.Exists)
                {
                    Directory.CreateDirectory(Server.MapPath("../Company/" + TypeName + "/"));
                }
            }
            //检查上传路径是否已经包含此文件
            bool SaveAs = true;
            bool fileOK = false;
            string fn = System.IO.Path.GetFileName(this.FindFile.PostedFile.FileName);
            string[] str = Directory.GetFiles(ViewState["Path"].ToString());
            string fileException = System.IO.Path.GetExtension(fn).ToLower();
            string[] allowedException ={ ".doc", ".txt" };
            if (str.Length != 0)
            {//目录下有文件时做出比较
                for (int j = 0; j < str.Length; j++)
                {
                    if (System.IO.Path.GetFileName(str[j]) == System.IO.Path.GetFileName(FindFile.PostedFile.FileName))
                    {
                        SaveAs = false;
                    }
                }
                if (SaveAs)
                {
                    for (int i = 0; i < hif.Count; i++)
                    {//检查数组当中是否已经存在此文件
                        HtmlInputFile HIF = hif[i] as HtmlInputFile;
                        if (System.IO.Path.GetFileName(HIF.Value) == System.IO.Path.GetFileName(FindFile.PostedFile.FileName))
                        {
                            SaveAs = false;
                        }
                    }
                    if (SaveAs)
                    {

                        for (int j = 0; j < allowedException.Length; j++)
                        {
                            if (fileException == allowedException[j])
                                fileOK = true;
                        }
                        if (fileOK)
                        {
                            hif.Add(FindFile);
                            this.FileLb.Text = System.IO.Path.GetFileName(FindFile.PostedFile.FileName) + " 上传成功!";
                        }
                        else
                        {
                            this.FileLb.Text = "请上传.doc文件,或.txt文件!";
                        }
                    }
                    else
                    {
                        this.FileLb.Text = System.IO.Path.GetFileName(FindFile.PostedFile.FileName) + "   文件已经上传,请不要重复上传!";
                    }
                }
                else
                {
                    this.FileLb.Text = System.IO.Path.GetFileName(FindFile.PostedFile.FileName) + "   文件已经存在,请检查company下的文件!";
                }

            }
            else
            {//目录下无文件直接保存!
                for (int i = 0; i < hif.Count; i++)
                {//检查数组当中是否已经存在此文件
                    HtmlInputFile HIF = hif[i] as HtmlInputFile;
                    if (hif.Count >= 1)
                    {
                        if (System.IO.Path.GetFileName(HIF.Value) == System.IO.Path.GetFileName(FindFile.PostedFile.FileName))
                        {
                            SaveAs = false;
                        }
                    }
                    else
                    {
                        SaveAs = true;
                    }
                }
                if (SaveAs)
                {
                    for (int j = 0; j < allowedException.Length; j++)
                    {
                        if (fileException == allowedException[j])
                            fileOK = true;
                    }
                    if (fileOK)
                    {
                        hif.Add(FindFile);
                        this.FileLb.Text = System.IO.Path.GetFileName(FindFile.PostedFile.FileName) + " 上传成功!";
                    }
                    else
                    {
                        this.FileLb.Text = "请上传.doc文件,或.txt文件!";
                    }
                }
                else
                {
                    this.FileLb.Text = System.IO.Path.GetFileName(FindFile.PostedFile.FileName) + "   文件已经上传,请不要重复上传!";
                }
            }
            Binddatalist(GetTable());
       }
        protected void returnBt_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/DocumentManage/Document_View.aspx?tag=" + this.TypeDDL.SelectedValue);
        }
        protected DataTable GetTable()
        {
            DataTable dt=new DataTable();
            DataTable table = new DataTable();
            table.Columns.Add("fileName");
            table.Columns.Add("fileid");
            hif.TrimToSize();
            int i = 0;
            foreach(System.Web.UI.HtmlControls.HtmlInputFile HIF in hif)
            {
                DataRow row =table.NewRow();
                string fn = System.IO.Path.GetFileName(HIF.PostedFile.FileName);
                row["fileName"] = fn;
                row["fileid"] = i++;
                table.Rows.Add(row);
            }
            dt = table;
            return dt;
        }
        protected void saveBt_Click(object sender, EventArgs e)
        {
           string DocumentID = "-1";
           if (this.titleTB.Text != "")
           {
            if (ViewState["Path"] != null)
            {//执行代有附件的保存
                string baseLocation = ViewState["Path"].ToString();

                string status = "";
               
                int Document_AttachStatus = -1;
                int Status = -1;

                this.FileLb.Text = "";
                Document_AttachStatusLb.Text = "";
                this.labDetial.Text = "";
                int i = 0;
            
                    foreach (System.Web.UI.HtmlControls.HtmlInputFile HIF in hif)
                    {
                        try
                        {
                            i++;
                            string fn = System.IO.Path.GetFileName(HIF.PostedFile.FileName);
                            if (DocumentID == "-1")
                            {//生成CompanyDocument内的唯一DocumentID
                                DocumentID = DateTime.Now.Date.ToString("yyyyMMdd") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
                            }
                            if (i == 1)
                            {//多文件上传只插入一个DocumentID
                                if (Session["UserID"] != null)
                                {
                                    string strCmd1 = "INSERT INTO CompanyDocument(DocumentID,WriteID,TypeID,Tilte,Content) VALUES('"
                                              + DocumentID + "','" + Session["UserID"].ToString() + "','" + this.TypeDDL.SelectedValue + "','" + this.titleTB.Text
                                              + "','" + this.ContentTB.Text + "')";
                                    Status = SQLda.ExecuteSQL(strCmd1);
                                }
                                else
                                {
                                    Response.Write("<script>alert('提示:重新登陆!')</script>");
                                }
                            }
                            string Txt = "SELECT * FROM Document_Attach";
                            dt = SQLda.GetTable(Txt);
                            if (dt.Rows.Count != 0)
                            {//Document_Attach表内有数据进行判断
                                bool InsertAttach = true;

                                for (int j = 0; j < dt.Rows.Count; j++)
                                {
                                    if (dt.Rows[j]["Url"].ToString() == HIF.PostedFile.FileName.Replace(@"//", @"/"))
                                    {
                                        InsertAttach = false;
                                    }
                                }
                                if (InsertAttach)
                                {
                                    string strTxt = "INSERT INTO Document_Attach(DocumentID,Url) VALUES('"
                                                                                  + DocumentID + "','" + baseLocation + fn + "')";
                                    Document_AttachStatus = SQLda.ExecuteSQL(strTxt);
                                }
                                else
                                {
                                    Document_AttachStatusLb.Text = "数据库当中已经存在此文件,请重新命名!";
                                }
                            }
                            else
                            {//Document_Attach表内无数据,直接插入
                                string strTxt = "INSERT INTO Document_Attach(DocumentID,Url) VALUES('"
                                               + DocumentID + "','" + baseLocation + fn + "')";
                                Document_AttachStatus = SQLda.ExecuteSQL(strTxt);
                            }
                            if (Document_AttachStatus > 0)
                            {
                                HIF.PostedFile.SaveAs(baseLocation + fn);
                                filesUploaded++;
                                status += fn + "<br>";
                                labDetial.Text = status + " 文件上传成功:<br>";
                            }

                        }
                        catch (Exception err)
                        {
                            labDetial.Text = "错误 文件保存 " + baseLocation
                                                               + "<br>" + err.ToString();
                        }
                    }
              
            
            }
            else
            {//执行无附件的保存
                if (DocumentID == "-1")
                {//生成CompanyDocument内的唯一DocumentID
                    DocumentID = DateTime.Now.Date.ToString("yyyyMMdd") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString();
                }
        
                if (Session["UserID"] != null)
                {
                    string strCmd1 = "INSERT INTO CompanyDocument(DocumentID,WriteID,TypeID,Tilte,Content) VALUES('"
                              + DocumentID + "','" + Session["UserID"].ToString() + "','" + this.TypeDDL.SelectedValue + "','" + this.titleTB.Text
                              + "','" + this.ContentTB.Text + "')";
                    int Status = SQLda.ExecuteSQL(strCmd1);
                }
                else
                {
                    Response.Write("<script>alert('提示:重新登陆!')</script>");
                }
             
            }
              hif.Clear();
              this.titleTB.Text = "";
              this.ContentTB.Text = "";
              this.labDetial.Text = "保存成功!";
              Binddatalist(GetTable());
            }
            else
            {//this.titleTB.Text == ""
                labDetial.Text = "提示:请填写文档标题";
                Binddatalist(GetTable());
                return;
            }
        }
        protected void viewAttachDL_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "attachImgBt")
            {
                int fileid =Int32.Parse(e.CommandArgument.ToString());
                hif.RemoveAt(fileid);
                Binddatalist(GetTable());
                this.FileLb.Text = "";
                Document_AttachStatusLb.Text = "";
                this.labDetial.Text = "";
             }
        }
}//end_class
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值