Loading

上传文档 - FileUpload

前台页面:

 <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" /><br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
</div>

 

后台代码:

protected void Button1_Click(object sender, EventArgs e)
        {
            NewMethod();
        }

        private void NewMethod()
        {
            //上传文件到指定文件夹
            string fileName = "";
            string fileExt = "";
            string strName = "";

            //从上传的文件流中提取所有文件并保存到数据库
            for (int i = 0; i < this.Request.Files.Count; i++)
            {
                fileName = this.Request.Files[i].FileName.Substring(this.Request.Files[i].FileName.LastIndexOf("\\") + 1);
                fileExt = fileName.Substring(fileName.LastIndexOf(".") + 1);

                if (IsUploadFile(fileName.Substring(fileName.LastIndexOf(".") + 1)))
                {
                    byte[] fileData = new byte[this.Request.Files[i].ContentLength];
                    this.Request.Files[i].InputStream.Read(fileData, 0, this.Request.Files[i].ContentLength);

                    var Files = Request.Files[i];
                    try
                    {
                        strName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + fileExt;
                        Files.SaveAs(Server.MapPath("../Upload/file/") + strName);

                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }

                }

                else
                {
                    string msg = "只能上传office、pdf及压缩文件!";
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(),"alert('" + msg + "');", true);
                    return;

                }

            }

            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(),"alert('文件上传成功');", true);
        }

public bool IsUploadFile(string fileExt) { if (fileExt != "") { if (fileExt != "doc" && fileExt != "docx" && fileExt != "xls" && fileExt != "xlsx" && fileExt != "ppt" && fileExt != "pptx" && fileExt != "pdf" && fileExt != "rar" && fileExt != "zip") { return false; } else { return true; } } else { return false; } }

 

posted @ 2012-09-24 11:30  The Mechanic  阅读(293)  评论(0编辑  收藏  举报