HTML <input type="file">结合asp.net的一个文件上传示例

HTML的代码:(关键是要在form里设置enctype="multipart/form-data",这样才能在提交表单时,将文件以二进制流的形式传输到服务器)

    <form id="form1" runat="server"  method="post" enctype="multipart/form-data">
    <div>
    <input type="file" />
     <asp:Button ID="btnUpload" runat="server"  Text="开始上传" onclick="btnUpload_Click" />
    </div>
    </form>

aps.net后台代码(C#):

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //int intCount = RequestClass.GetFormInt("hdcount", -1);
            HttpFileCollection Files = HttpContext.Current.Request.Files;
            for (int i = 0; i < Files.Count; i++)
            {
                HttpPostedFile PostedFile = Files[i];
                if (PostedFile.ContentLength > 0)
                {
                    string FileName = PostedFile.FileName;
                    string strExPrentFile = FileName.Substring(FileName.LastIndexOf(".") + 1);

                    string sFilePath = "/uploadfile/hotel/" + StringClass.makeFileName24() + i + strExPrentFile;
                    PostedFile.SaveAs(Server.MapPath(sFilePath));
                }
                else
                {
                    //this.LabMessage.Text = "不能上传空文件";
                }
            }
        }

 

posted @ 2012-12-14 11:53  ``炯``  阅读(5764)  评论(0编辑  收藏  举报