杨应红的WEB技术文档
WEB相关技术
想实现任意多个文件上传的功能,点击一次按钮可以添加一个文件上传框,以前在网络硬盘上看到过。javascript我知道怎么实现任意添加上传文件控件,问题是添加的是html控件,我不懂怎么让服务器端可以获取文件。

    于是上google搜索“asp.net 多文件上传”,还真找到一篇文件,标题为《在asp.net中实现多文件上传》,文章里面是vb.net实现的,功能和我要的一模一样,我主要是要看服务器端怎么获取客户端上传的文件,看了文中的代码,原来这么简单,system.web.httpcontext.current.request.files就包含客户端浏览器上传的文件了,我用c#写了一段简单的代码,原本以为应该可以了,结果出乎意料上传3个图片system.web.httpcontext.current.request.files返回的文件格式还是0个。

    不知道什么原因,看看代码,这么简单不可能些错啊,再看看google搜索结果里的另外几篇文章,发现我看的第一篇不是原做,作者的网站上原作的实例有两个版本,一个是vb.net一个是c#的,现在我不用自己写了,复制原文的代码到本地,运行,果然可以啊,那我写的代码怎么不行?反复比对我的代码和文章中代码的区别,试了几个地方,最后发现和其他地方都没有关系,原因出在<form id="form1" runat="server" enctype="multipart/form-data"> 的enctype属性上,vs 2005建的页面里没有这个属性,而文章实例里有,我后来加上enctype="multipart/form-data"后system.web.httpcontext.current.request.files就能z正常获取文件个数了。

    大概是vs 2003建的页面默认有这个属性吧,否则这么重要的属性作者应该会在文章中提到的。

参考:
《在asp.net中实现多文件上传》

我做的试验代码:

<%@ page language="c#" autoeventwireup="true" codebehind="default.aspx.cs" inherits="demo._default" %>

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<script language="javascript">
function addfile()
{
 var str = <input type="file" size="50" name="file">
 document.getelementbyid(myfile).insertadjacenthtml("beforeend",str)
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>untitled page</title>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
           <input type="button" value="增加(add)" onclick="addfile()">
          <input onclick="this.form.reset()" type="button" value="重置(reset)">
          <asp:button runat="server" text="上传" id="upload" onclick="upload_click1" ></asp:button>
    <div id="myfile">
         <input type="file" name="file" />
    </div>
    </form>
</body>
</html>

using system;
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;

namespace demo
{
    public partial class _default : system.web.ui.page
    {
        protected void page_load(object sender, eventargs e)
        {
        }
        protected void upload_click1(object sender, eventargs e)
        {

            httpfilecollection _files = system.web.httpcontext.current.request.files;

            for (int i = 0; i < _files.count; i++)
            {
                _files[i].saveas(server.mappath("~/files/" + _files[i].filename));
            }
        }
    }
}

posted on 2007-02-05 09:36  落尘  阅读(294)  评论(0编辑  收藏  举报