当前位置:编程学习 > C#/ASP.NET >>

c# asp.net大文件上传(大于1G)

如题,如何使用C#和ASP.net实现大文件的上传,这个文件的容量的很大的,基本都是要对大于1G的文件处理,希望有高手过来指点下?下面是下载的一个代码,不过是多文件的上传,而且效率不高.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

//51aspx
namespace MutiFileUpload
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            int FileNum = 0;
            string filepath = Server.MapPath("./") + "UploadFile";
            string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hfc[i].ContentLength > 0)
                {
                    hpf.SaveAs(filepath + "/" + filename + System.IO.Path.GetFileName(hpf.FileName));
                    FileNum++;
                }
                else
                {
                    //Response.Write(alert("请选择你要上传的文件!"));
                    //跳出for循环
                    i = hfc.Count;
                    break;
                }                
            }
           // Response.Write("<script>alert('上传成功!')</script>");
            Response.Write("共上传成功的文件个数为:" + FileNum + "个");
            FileNum = 0;
        }
    }
}
但是上面这段程序也有个问题,脚本不能运行,我想知道原因是什么??
--------------------编程问答-------------------- asp.net iis 都有大小限制的, 是否能配置到支持 1 G 的不知道,

你需要处理断线后的续传问题. --------------------编程问答--------------------         if (fupUrl.PostedFile.ContentLength > 1024000)
        {
            fileOk = false;
            Helper.CommonTools.AlertInfo("上传的作品大小不能超过3M!", "Upload.aspx");
            return;
        } --------------------编程问答-------------------- 考虑用其他的吧!比如Flex,Ocx什么的好点吧? --------------------编程问答-------------------- 我现在的要求就是要处理大文件的上传问题,小于1G的都没什么用,而且怎么处理超过1G的断点后续上传问题 --------------------编程问答-------------------- 路过学习 --------------------编程问答-------------------- system.web> </system.web>之间 
<httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="21000" executionTimeout="300" /> 
maxRequestLength:设置上传文件的最大值,单位:KB。(默认是4096KB,即4M) 
executionTimeout:设置超时时间,单位:秒。(默认是90秒) 
用HttpWorkerRequest,GetPreloadedEntityBody 和 ReadEntityBody方法从IIS为ASP.NET建立的pipe里分块读取数据 
http://topic.csdn.net/u/20091029/09/e5dc6f96-f1fb-4b61-b68d-546622b4b3e3.html --------------------编程问答-------------------- 你写个函数  用线程分段上传
一下一下上传  不然会卡死的  太大的不行
貌似现在又大文件上传的控件
自己写一个比较好 --------------------编程问答-------------------- Setting up Web.config to allow uploading of large files by ASP .NET applications

This article shows how to setup Web.config to allow uploading of files larger than 4 MB by ASP.NET applications.




Multiple File Upload With Progress Bar Using Flash and ASP.NET

How to use Flash to upload multiple files in a medium-trust hosting environment



--------------------编程问答-------------------- 少不了要支持断点续传功能! --------------------编程问答-------------------- ASP.Net file post direct to disk with upload file progress support

This module gives developers a way to intercept multi-part form posts in ASP.Net and store the data directly to disk without going direct to memory. It also provides a way to extract the file progress from an external window. Written in C# for backend, and Javascript / Atlas for the progress bar.


Introduction

ASP.NET is a very nice and fast way to program small to enterprise level websites fast and efficiently. Most controls are perfect for any web development needed however the FileUpload control really has some short comings. Back when I used .net 1.1, I did some testing to see how the control worked and handled large files and was very unpleased.

I tried to upload a huge 1 or 2 gig file. I found myself with a problem where my web page would error, and the memory was never released. I left it at that, and did not mess with it anymore.  I though for sure that the 2.0 framework would have fixed that problem but it appears that we were not that lucky (at least not that I could find).

Anyhow the project I was working on requires that I have control of what my users do. You never know when someone is going to try and upload some huge file on purpose or accident.


--------------------编程问答-------------------- 楼上的太强了,看不懂英文。。。。。 --------------------编程问答-------------------- 帮顶。 --------------------编程问答-------------------- 呵呵.Up --------------------编程问答-------------------- 关注
--------------------编程问答-------------------- 继点续传没做过,但首先还得解决上传进度的问题吧,我关注 --------------------编程问答--------------------
引用 8 楼 goga21cn 的回复:
Setting up Web.config to allow uploading of large files by ASP .NET applications

This article shows how to setup Web.config to allow uploading of files larger than 4 MB by ASP.NET applications.




Multiple File Upload With Progress Bar Using Flash and ASP.NET

How to use Flash to upload multiple files in a medium-trust hosting environment



这个东西 我改成了中文的

但是并不能解决 楼主的 上传 1G 的要求 --------------------编程问答-------------------- 关注。。 --------------------编程问答-------------------- http://download.csdn.net/source/675091

LZ 去看看。。。。我没试!!!
好用,记得 发表下。。。 --------------------编程问答-------------------- Mark一下,回头再看 --------------------编程问答-------------------- 小关注一下 --------------------编程问答-------------------- web 上 上传那么大 干什么啊  --------------------编程问答--------------------
引用 16 楼 alex1987214 的回复:
引用 8 楼 goga21cn 的回复:
 Setting up Web.config to allow uploading of large files by ASP .NET applications

 This article shows how to setup Web.config to allow uploading of files larger than 4 MB by ASP.NET applications.


 Multiple File Upload With Progress Bar Using Flash and ASP.NET

 How to use Flash to upload multiple files in a medium-trust hosting environment





 这个东西 我改成了中文的

 但是并不能解决 楼主的 上传 1G 的要求



这个仅仅是一个设置而已 --------------------编程问答-------------------- 10楼贴的那个类很强大 --------------------编程问答-------------------- 写这个要支持多用户上传文件而且文件的基本都是大于1G的,虽然在ASP.NET里面可以设置文件上传的大小,不过好像不能达到我的要求,希望高手来解决下 --------------------编程问答--------------------
引用 24 楼 qishao45741100 的回复:
写这个要支持多用户上传文件而且文件的基本都是大于1G的,虽然在ASP.NET里面可以设置文件上传的大小,不过好像不能达到我的要求,希望高手来解决下


设置只是第一步,第二步用哪个文件上传类试试 --------------------编程问答-------------------- 关注中 --------------------编程问答-------------------- 标记一下,等神人出现 --------------------编程问答-------------------- 1G,怎么会要上传这么大的文件?做FTP吧 --------------------编程问答-------------------- 我有activex文件上传的控件 --------------------编程问答-------------------- 支持大文件上传,断点续传 --------------------编程问答-------------------- 断点续传呗。

把文件分割,用线程分块一段一段的传吧 --------------------编程问答-------------------- 还是分割后上传吧 --------------------编程问答-------------------- 路过,学习
没有试过这样大的文件上传 --------------------编程问答-------------------- 分割上传 --------------------编程问答-------------------- 路过,学习 --------------------编程问答-------------------- mark  up

--------------------编程问答-------------------- mark --------------------编程问答--------------------

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Reflection; 

namespace myHttpModule
{
 /// <summary>
 /// HttpUploadModule 的摘要说明。
 /// </summary>
 public class HttpUploadModule: IHttpModule
 {
  public HttpUploadModule()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }
  public void Init(HttpApplication application)
  {
   application.BeginRequest += new EventHandler(this.Application_BeginRequest);
   application.EndRequest += new EventHandler(this.Application_EndRequest);
   application.Error += new EventHandler(this.Application_Error);
  }

  public void Dispose()
  {
  }

  private void Application_BeginRequest(Object sender, EventArgs e)
  {
   HttpApplication app = sender as HttpApplication;

   // 如果是文件上传
   if (IsUploadRequest(app.Request))
   {
    // 返回 HTTP 请求正文已被读取的部分。
    HttpWorkerRequest request = GetWorkerRequest(app.Context);
    Encoding encoding = app.Context.Request.ContentEncoding;

    int bytesRead = 0; // 已读数据大小
    int read; // 当前读取的块的大小
    int count = 8192; // 分块大小
    byte[] buffer; // 保存所有上传的数据
    byte[] tempBuff = null;
    
    if (request != null)
    {
     tempBuff = request.GetPreloadedEntityBody();
    }
    if (tempBuff != null)
    {
     // 获取上传大小
     // 
     long length = long.Parse(request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));
     
     buffer = new byte[length];
     count = tempBuff.Length; // 分块大小

     // 将已上传数据复制过去
     //
     Buffer.BlockCopy(tempBuff, 0, buffer, bytesRead, count);

     // 开始记录已上传大小
     //
     bytesRead = tempBuff.Length;

     // 循环分块读取,直到所有数据读取结束
     //
     while (request.IsClientConnected() &&
      !request.IsEntireEntityBodyIsPreloaded() &&
      bytesRead < length
      )
     {
      // 如果最后一块大小小于分块大小,则重新分块
      //
      if (bytesRead + count > length)
      {
       count = (int)(length - bytesRead);
       tempBuff = new byte[count];
      }

      // 分块读取
      //
      read = request.ReadEntityBody(tempBuff, count);
      
      // 复制已读数据块
      //
      Buffer.BlockCopy(tempBuff, 0, buffer, bytesRead, read);
      
      // 记录已上传大小
      //
      bytesRead += read;

     }
     if (
      request.IsClientConnected() &&
      !request.IsEntireEntityBodyIsPreloaded()
      )
     {
    
      // 传入已上传完的数据
      //
      InjectTextParts(request, buffer);

      // 表示上传已结束

     }
    }
   }
  }

  /// <summary>
  /// 结束请求后移除进度信息
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void Application_EndRequest(Object sender, EventArgs e)
  {

  } 

  /// <summary>
  /// 如果出错了设置进度信息中状态为“Error”
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void Application_Error(Object sender, EventArgs e)
  {

  }

  HttpWorkerRequest GetWorkerRequest(HttpContext context)
  {

   IServiceProvider provider = (IServiceProvider)HttpContext.Current;
   return (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
  }

  /// <summary>
  /// 传入已上传完的数据
  /// </summary>
  /// <param name="request"></param>
  /// <param name="textParts"></param>
  void InjectTextParts(HttpWorkerRequest request, byte[] textParts)
  {
   BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; 
   
   Type type = request.GetType(); 
   
   while ((type != null) && (type.FullName != "System.Web.Hosting.ISAPIWorkerRequest"))
   { 
    type = type.BaseType; 
   }

   if (type != null)
   {
    type.GetField("_contentAvailLength", bindingFlags).SetValue(request, textParts.Length); 
    type.GetField("_contentTotalLength", bindingFlags).SetValue(request, textParts.Length);
    type.GetField("_preloadedContent", bindingFlags).SetValue(request, textParts); 
    type.GetField("_preloadedContentRead", bindingFlags).SetValue(request, true);
   }
  }

  /// <summary>
  /// 是否为附件上传
  /// 判断的根据是ContentType中有无multipart/form-data
  /// </summary>
  /// <param name="request"></param>
  /// <returns></returns>
  bool IsUploadRequest(HttpRequest request)
  {
   return request.ContentType.ToLower()=="multipart/form-data";
  }

 }
}

需要在web.config中加入

   <httpRuntime executionTimeout="600" maxRequestLength="1048576"/> 

 <httpModules>

  <add name="HttpUploadModule" type="myHttpModule" />
 </httpModules>

--------------------编程问答-------------------- 呵呵,向这样的要求,要买收费的控件才行了。

以前试用过几个,还算不错。 --------------------编程问答-------------------- 一般来说asp.net里只能传大约4mb的东西,但是实际需求下,可以采用很多方式比如flash,好像有个免费的flash可以上传的,lz搜索一下应该可以找到,再不行留个mail我好像有个 --------------------编程问答-------------------- 需要使用第三方控件,有免费的 --------------------编程问答-------------------- 通过网页来上传这么大的文件是不可取的,可以专门做个上传工具,或者上传控件,flash,active控件啥的。不过我没搞过~ --------------------编程问答-------------------- 只能说这样的需求很有变态 --------------------编程问答-------------------- slickupload. --------------------编程问答-------------------- mtom协议支持大文件分小块传输 --------------------编程问答--------------------
引用 8 楼 goga21cn 的回复:
Setting up Web.config to allow uploading of large files by ASP .NET applications

This article shows how to setup Web.config to allow uploading of files larger than 4 MB by ASP.NET applications.

……

这个是什么控件啊?能告诉一下吗? --------------------编程问答-------------------- http://www.evget.com/zh-CN/FeaturedArticle/Default.aspx?id=1
联系方式:qq 228184703 --------------------编程问答-------------------- 用NeatUpload上传控件,免费的!上传1G以上的文件没有问题,我曾经做过!但好像不支持断点续传! --------------------编程问答-------------------- --------------------编程问答-------------------- 我就纳闷了  谁这么有劲啊  老顶 09年的帖子   --------------------编程问答--------------------
引用 25楼 mjfei 的回复:
路过,学习
学习 --------------------编程问答-------------------- 其实一些控件就好的,也可以学习下下载工具的做法. --------------------编程问答-------------------- 好象有专门做大文本上传的源代码,你在网上找一找。 --------------------编程问答-------------------- 换方式吧,改用FTP上传吧,要不没等上传一半就会卡得不行了, --------------------编程问答-------------------- NTKO大文件上传控件,采用多线程技术,提供专业的大文件上传解决方案,是国内唯一支持断点续传上传的控件。可以轻松迅速将10G的大文件上传到WEB服务器,甚至更大文件的快速上传(仅受服务器端操作系统的限制),并采用独创技术,支持断点续传上载,以及一次选择并逐个上传多个文件。上传到WEB服务器的文件,通过web服务器编程支持,还可以采用迅雷,FLASHGET等支持断点续传下载的工具软件进行多线程,可续传的下载。NTKO大文件上传控件可支持除了Domino服务器之外的大部分WEB服务器(因domino数据库如果保存大量大附件性能明显下降,不予支持),并且可以在浏览器中通过JScript或者VBScript使用控件提供的属性和方法进行操作。 --------------------编程问答-------------------- FortuneBase中
NickLee.Common.Configuration.UploadLocationProviderHandler

参考FortuneBase
www.cnblogs.com/mail-ricklee --------------------编程问答-------------------- 两年了,还没结贴 --------------------编程问答-------------------- 不会吧,你想干什么呀??????? --------------------编程问答-------------------- 这个一般要用第三方控件来实现。在IE下面用ActiveX,在FireFox下面用NPAPI。 --------------------编程问答-------------------- 此控件支持100G文件的断点续传操作,提供了完善的开发文档,支持文件MD5验证,支持文件批量上传。
文件MD5值计算进度:

文件MD5值计算完毕

服务器根据MD5检测是否存在相同文件

续传文件

从服务器加载文件列表

文件上传中

文件上传完毕

上传文件夹

与Discuz!X2整合-后台安装断点续传控件

与Discuz!X2整合-后台启用断点续传控件

与Discuz!X2整合-后台断点续传控件启用成功

与Discuz!X2整合-前台发帖页面

与Discuz!X2整合-上传

--------------------编程问答--------------------
引用 60 楼  的回复:
此控件支持100G文件的断点续传操作,提供了完善的开发文档,支持文件MD5验证,支持文件批量上传。
文件MD5值计算进度:

文件MD5值计算完毕

服务器根据MD5检测是否存在相同文件

续传文件

从服务器加载文件列表

文件上传中

文件上传完毕

上传文件夹

与Discuz!X2整合-后台安装断点续传控件

与Discuz!X2整合-后台启用断点续……

这个用户体验不错。最近正在做一个项目,正好需要这个功能。在网上找了许多HTTP断点续传控件都没有找到。先谢啦。能否把地址发一下。 --------------------编程问答--------------------
引用 61 楼  的回复:
引用 60 楼  的回复:

此控件支持100G文件的断点续传操作,提供了完善的开发文档,支持文件MD5验证,支持文件批量上传。
文件MD5值计算进度:

文件MD5值计算完毕

服务器根据MD5检测是否存在相同文件

续传文件

从服务器加载文件列表

文件上传中

文件上传完毕

上传文件夹

与Discuz!X2整合-后台安装断点续传控件

与Di……

这个是Xproer.HttpUploader3,可以在网上直接搜到。 --------------------编程问答--------------------
引用 62 楼  的回复:
引用 61 楼  的回复:

引用 60 楼  的回复:

此控件支持100G文件的断点续传操作,提供了完善的开发文档,支持文件MD5验证,支持文件批量上传。
文件MD5值计算进度:

文件MD5值计算完毕

服务器根据MD5检测是否存在相同文件

续传文件

从服务器加载文件列表

文件上传中

文件上传完毕

上传文件夹

与Discuz!X2整合-……

现在的应用越来越注重用户体验了。从QQ第一个推荐大附件上传功能以来,越来越多的互联网企业也开始重视这一块。不过良好的用户体验也的确能够给用户带来许多便利,。 --------------------编程问答--------------------
引用 63 楼  的回复:
引用 62 楼  的回复:

引用 61 楼  的回复:

引用 60 楼  的回复:

此控件支持100G文件的断点续传操作,提供了完善的开发文档,支持文件MD5验证,支持文件批量上传。
文件MD5值计算进度:

文件MD5值计算完毕

服务器根据MD5检测是否存在相同文件

续传文件

从服务器加载文件列表

文件上传中

文件上传完毕

上传文件夹……

没有用户体验搞个毛。难道现在上传文件还让用户手动一张张上传?难道用户想上传一个大文件还用FTP传? --------------------编程问答-------------------- 网上有一个Web大文件断点续传控件(Xproer.HttpUploader4):http://www.cnblogs.com/xproer/archive/2012/05/29/2523757.html
此控件支持100G文件的断点续传操作,提供了完善的开发文档,支持文件MD5验证,支持文件批量上传。
页面调用示例代码:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>HTTP断点续传控件与MySQL数据库演示页面(UTF-8)</title>
    <link href="HttpUploader/HttpUploader.css" type="text/css" rel="Stylesheet"/>
    <script type="text/javascript" charset="utf-8" src="HttpUploader/FileLister.js"></script>
    <script type="text/javascript" charset="utf-8" src="HttpUploader/HttpUploader.js"></script>
    <script type="text/javascript" charset="utf-8" src="HttpUploader/combinbox.js"></script>
    <script type="text/javascript" src="HttpUploader/jquery-1.3.2.min.js"></script>
    <script language="javascript" type="text/javascript">
     var cbItemLast = null;
     var cbMgr = new CombinBoxMgr();

     $(document).ready(function()
     {
     cbMgr.LoadInControl("FilePanel");
     cbMgr.Init();
     });
    </script>
</head>
<body>
<div id="FilePanel"></div>
</body>
</html>

资源下载:
CAB安装包
开发文档
ASP.NET-ACCESS示例
ASP.NET-SQL2005示例
JSP-ACCESS-GB2312示例
JSP-ACCESS-UTF8示例
JSP-SqlServer2005-UTF8示例
JSP-MySQL-UTF8示例
JSP-WebLogic-ACCESS-GB2312示例
JSP-WebLogic-ACCESS-UTF8示例
PHP-MySQL-UTF8示例
Chrome,Firefox,IE断点续传控件示例(以下示例已整合IE32,IE64,Firefox,Chrome平台的插件)
ASP.NET-ACCESS示例
JSP-ACCESS-GB2312示例
JSP-ACCESS-UTF8示例
JSP-SqlServer2005-UTF8示例
JSP-MySQL-UTF8示例
PHP-MySQL-UTF8示例
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,