zoukankan      html  css  js  c++  java
  • 上传文档 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; } }
  • 相关阅读:
    Log4net 在framework Client中编译失败
    (MVC)从客户端中检测到有潜在危险的 Request.Form 值
    RichText设置高亮 (未完)
    1转换为00001等
    简单的MDX案例及说明(3)
    兼容型Word 并带传统读法
    Visual Studio 2010添加新项缺失[ADO.NET 实体数据模型]解决方法
    SQL Server 的优化方法(续转)
    两个有用的委托:Func和Action
    SQL Server 的优化方法(转)
  • 原文地址:https://www.cnblogs.com/JiangXiaoTian/p/2699801.html
Copyright © 2011-2022 走看看