用HttpFileCollection实现多文件上传的例子

注意:页面Form的属性一定要设为enctype="multipart/form-data"

 

test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebTest.Test" %>

<!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">
    <title></title>
</head>
<body>
     <form id="form1" runat="server" enctype="multipart/form-data">
    <div>    
        <input id="File1" type="file" name="File1" />
        <br />
        <input id="File2" type="file" name="File2" />
        <br />
        <asp:Button 
            ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    
    </div>
    </form>
</body>
</html>

 

下面是后台代码:

test.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WebTest
{
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 客户端点击确定后向服务器发送post,下面是服务器端的处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            //HttpFileCollection提供对客户端上传文件的访问
            if (Request.Files != null)
            {
                HttpFileCollection files = Request.Files;//获取由客户端上传的文件的集合
                string fileName;
                for (int i = 0; i < files.Count; i++)
                {
                    if (files[i].ContentLength <= 0) //上传文件大小为空
                    {
                        continue;
                    }
                    fileName = Path.GetFileName(files[i].FileName);//获取文件名和扩展名(信息搜集.xls)
                    string path = Request.MapPath(fileName);//将指定的虚拟地址映射到服务器物理地址E:\VSProject\EFDemo\WebTest\信息搜集.xls
                    files[i].SaveAs(path);//按照服务器物理路径保存文件
                }
            }

        }
    }
}

 提示:如果文件已经存在,就会覆盖掉原先的文件。

转载地址:http://www.cnblogs.com/aivdesign/articles/1237063.html

 

posted @ 2012-08-29 10:06  金河  阅读(386)  评论(0编辑  收藏  举报