ASP.NET C#OutofMemoryException大文件上载
发布时间:2020-12-16 03:58:33 所属栏目:asp.Net 来源:网络整理
导读:我有以下文件上传处理程序: public class FileUploader : IHttpHandler{ public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; context.Response.ContentType = "text/html"; context.Response.ContentEncoding = Sy
我有以下文件上传处理程序:
public class FileUploader : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; context.Response.ContentType = "text/html"; context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); var tempPath = request.PhysicalApplicationPath + "FilesTempFiles"; byte[] buffer = new byte[request.ContentLength]; using (BinaryReader br = new BinaryReader(request.InputStream)) { br.Read(buffer,buffer.Length); } var tempName = WriteTempFile(buffer,tempPath); context.Response.Write("{"success":true}"); context.Response.End(); } public bool IsReusable { get { return true; } } private string WriteTempFile(byte[] buffer,string tempPath) { var fileName = GetUniqueFileName(tempPath); File.WriteAllBytes(tempPath + fileName,buffer); return fileName; } private string GetUniqueFileName(string tempPath) { var guid = Guid.NewGuid().ToString().ToUpper(); while (File.Exists(tempPath + guid)) { guid = Guid.NewGuid().ToString().ToUpper(); } return guid; } } 当我上传大文件时,这会导致OutOfMemoryException.有人能说出使用这样的处理程序上传大文件的正确方法吗? 解决方法
无需将文件加载到内存中即可将其写入某处.你应该使用一个小缓冲区(可能是8k),并循环流.或者,使用4.0,CopyTo方法.例如:
using(var newFile = File.Create(tempPath)) { request.InputStream.CopyTo(newFile); } (它为您执行小缓冲区/循环,默认情况下使用4k缓冲区,或允许通过重载传递自定义缓冲区大小) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – MVC Ajax.BeginForm替换奇怪的行为
- ASP.NET内置用户配置文件与旧stile用户类/表
- 使用ASP.NET Core 2.0进行用户管理
- asp.net-mvc – 控制器和操作方法之间丢失的会话变量
- asp.net核心中的Request.CreateResponse
- asp.net-mvc-3 – 有没有办法通过html.actionlink在ASP.NET
- asp.net-mvc – 使用ASP.NET MVC的RESTful Web服务
- asp.net – 如何使用IIS重定向URL中的额外正斜杠
- asp.net – SQL Server 2005网络IO等待时间(ASYNC_NETWORK_
- 初识ABP vNext(2):ABP启动模板
推荐文章
站长推荐
- asp.net – 多个Application_Start事件触发
- asp.net-mvc – 如何使用ASP.NET身份(OWIN)访问F
- 带有子项的ASP.NET自定义/用户控件
- .net – 可以为空的枚举类型的奇怪行为
- asp.net-mvc – 在.NET MVC 3中使用REST Web服务
- asp.net-mvc – 检查上传的文件是否是C#ASP.NET
- 记一次ASP.NET MVC性能优化(实际项目中)
- Asp.Net数据控件引用AspNetPager.dll分页实现代码
- asp.net-mvc – 如何在ASP.NET MVC视图中访问路由
- 单元测试 – 如何在ASP MVC 5(Microsoft.AspNet.
热点阅读