[ZT] ASP.NET 关于大文件上传问题

来源:互联网 发布:找最大值 java 方法 编辑:程序博客网 时间:2024/05/15 03:20

[ZT]http://bbs.51aspx.com/showtopic-3958-1.html

 

 

 

第一部分:

  首先我们来说一下如何解决ASP.net中的文件上传大小限制的问题,我们知道在默认情况下ASP.NET的文件上传大小限制为2M,一般情况下,我们可以采用更改Web.Config文件来自定义最大文件大小,如下:

  这样上传文件的最大值就变成了4M,但这样并不能让我们无限的扩大 MaxRequestLength的值,因为ASP.NET会将全部文件载入内存后,再加以处理。解决的方法是利用隐含的 HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法从IIS为ASP.NET 建立的pipe里分块读取数据。实现方法如下:

 

 

IServiceProvider Provider = (IServiceProvider)HttpContext.Current;

            HttpWorkerRequest workRequest = (HttpWorkerRequest)Provider.GetService(typeof(HttpWorkerRequest));

            byte[] bs = workRequest.GetPreloadedEntityBody();

            if (!workRequest.IsEntireEntityBodyIsPreloaded())

            {

                int n = 1024;

                byte[] bs2 = new byte[n];

                while (workRequest.ReadEntityBody(bs2, n) > 0)

                {

 

                }

            }

 

 

 

 

 

 

第二部分:

  下面我们来介绍如何以文件形式将客户端的一个文件上传到服务器并返回上传文件的一些基本信息。

   我们可以在配置文件中限制上传文件的格式(App.Config):

 

    <?XML version="1.0" encoding="gb2312" ?>

    <Application>

      <FileUpLoad>

        <Format>.jpg|.gif|.png|.bmp

      </FileUpLoad>

    </Application>

 

 

 

        /// <summary>

        ///

        /// </summary>

        /// <param name="InputFile">The control of 'input type='file' field.</param>

        /// <param name="filePath">Server file path.</param>

        public void UpLoadFile(HtmlInputFile InputFile, string filePath)

        {

            string fileName = InputFile.PostedFile.FileName;

            string saveName = Path.GetFileName(fileName);

 

            /* METHOD 1 */

            //HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];

            //string phyPath = HttpContext.Current.Server.MapPath("./file/");

            //if (!Directory.Exists(phyPath)) Directory.CreateDirectory(phyPath);

            //postedFile.SaveAs(phyPath + saveName);

 

            /* METHOD 2 */

            HttpPostedFile postedFile = InputFile.PostedFile;

            string phyPath = HttpContext.Current.Request.MapPath(fileName);

            postedFile.SaveAs(phyPath + fileName);

        }

然后我们在上传文件的时候就可以调用这个方法了,将返回的文件信息保存到数据库中,至于下载,就直接打开那个路径就OK了。

 

第三部分:

  这里我们主要说一下如何以二进制的形式上传文件以及下载。首先说上传,方法如下:

 

        public byte[] UpLoadFile(HtmlInputFile file)

        {

            HttpPostedFile upFile = file.PostedFile;

            int upFileLength = upFile.ContentLength;

            //客户端MIME类型

            string contentType = upFile.ContentType;

            byte[] FileArray = new Byte[upFileLength];

 

            Stream fileStream = upFile.InputStream;

 

            fileStream.Read(FileArray, 0, upFileLength);

            return FileArray;

        }


这个方法返回的就是上传的文件的二进制字节流,这样我们就可以将它保存到数据库了。下面说一下这种形式的下载,也许你会想到这种方式的下载就是新建一个 aspx页面,然后在它的Page_Load()事件里取出二进制字节流,然后再读出来就可以了,其实这种方法是不可取的,在实际的运用中也许会出现无法打开某站点的错误,我一般采用下面的方法:

  首先,在Web.config中加入:

<add verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/>
这表示我打开openfile.aspx这个页面时,系统就会自动转到执行RuixinOA.Web.BaseClass.OpenFile 这个类里的方法,具体实现如下:

 

    public class OpenFile : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

 

            DataSet ds = new DataSet();

            DataTable dt = ds.Tables[0];

            DataRow drow = dt.Rows[0];

            context.Response.Buffer = true;

            context.Response.Clear();

            context.Response.ContentType = drow["CContentType"].ToString();

            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(drow["CTitle"].ToString()));

            context.Response.BinaryWrite((Byte[])drow["CContent"]);

            context.Response.Flush();

            context.Response.End();

 

        }

        public bool IsReusable

        { get { return true; } }

    }

 

第四部分:

  这一部分主要说如何上传一个Internet上的资源到服务器。

  首先需要引用 System.Net 这个命名空间,然后操作如下:

HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("http://localhost/pwtest/webform1.aspx");
HttpWebResponse hwr = (HttpWebResponse)hwq.GetResponse();
byte[] bytes = new byte[hwr.ContentLength];
Stream stream = hwr.GetResponseStream();
stream.Read(bytes,0,Convert.ToInt32(hwr.ContentLength));
//HttpContext.Current.Response.BinaryWrite(bytes);

  HttpWebRequest 可以从Internet上读取文件,因此可以很好的解决这个问题。

原创粉丝点击