C# 上传大文件
上传大文件首先要修改web.config文件,否则上传报错。在web.config添加如下配置maxRequestLength表示能上传的最大文件值,单位是KB,requestLengthDiskThreshold表示超过多少KB之后的文件缓存到文件系统,不缓存在内存,以减轻内存负担。requestLengthDiskThreshold必须小于maxRequestLength
<configuration>
<system.web>
<httpRuntime maxRequestLength ="" requestLengthDiskThreshold =""/>
</system.web>
</configuration>
上传页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebFormLargeFile.aspx.cs" Inherits="WebApplication1.WebFormLargeFile" %> <!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>
<style type ="text/css" >
.fileList
{
margin-bottom :5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID ="lblFile" runat ="server" AssociatedControlID ="upFile" Text ="World Document:"></asp:Label>
<asp:FileUpload ID ="upFile" runat ="server" />
<asp:Button ID ="btnAdd" runat ="server" onclick="btnAdd_Click" Text ="上传" />
<hr />
<asp:Repeater ID ="rptFiles" runat ="server" DataSourceID ="srcFiles" >
<HeaderTemplate >
<ul class ="fileList">
</HeaderTemplate>
<ItemTemplate >
<li>
<asp:HyperLink ID ="lnkFile" runat ="server" Text ='<%#Eval("FileName") %>' NavigateUrl ='<%#Eval("Id","~/FileHandlerLarge.ashx?Id={0}") %>'></asp:HyperLink>
</li>
</ItemTemplate>
<FooterTemplate >
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
<asp:SqlDataSource ID="srcFiles" runat="server"
ConnectionString="Data Source=localhost;Initial Catalog=test;Integrated Security=True" ProviderName ="System.Data.SqlClient"
SelectCommand="SELECT * FROM [Files]"></asp:SqlDataSource>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Data; namespace WebApplication1
{
public partial class WebFormLargeFile : System.Web.UI.Page
{
const string connStr = "Data Source=localhost;Initial Catalog=test;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{ } protected void btnAdd_Click(object sender, EventArgs e)
{
if (upFile.HasFile)
{
if (CheckFileType(upFile.FileName))
{
AddFile(upFile.FileName, upFile.FileContent);
rptFiles.DataBind();
}
}
} private bool CheckFileType(string fileName)
{
return Path.GetExtension(fileName).ToLower() == ".doc";
} private void AddFile(string fileName,Stream upload)
{
using(SqlConnection conn=new SqlConnection(connStr))
{
string sql = "insert into Files (FileName) values(@FileName)\n select @Id=SCOPE_IDENTITY() ";
SqlCommand cmd = new SqlCommand(sql,conn);
cmd.Parameters.AddWithValue("@FileName", fileName);
SqlParameter IdParam= new SqlParameter("@Id", SqlDbType.Int);
IdParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(IdParam); conn.Open();
cmd.ExecuteNonQuery();
int id =Convert.ToInt32(IdParam.Value);
StoreFile(id, conn, upload);
} } private void StoreFile(int Id, SqlConnection conn, Stream upload)
{
int bufferLength = ;
BinaryReader reader = new BinaryReader(upload);//从流中读取字节数据
byte[] chuk = new byte[bufferLength];
chuk = reader.ReadBytes(bufferLength); SqlCommand cmd =new SqlCommand("update Files set FileBytes=@FileBytes where Id =@id",conn);
cmd.Parameters.AddWithValue("@id", Id);
cmd.Parameters.Add("@FileBytes", SqlDbType.VarBinary, bufferLength).Value = chuk;
cmd.ExecuteNonQuery(); //set 列名.write(表达式,@offset,@length)用表达式的值替换某列从开始索引@length长度字符
//set 列名.write(表达式,null,0)在某列末尾追加
//set 列名.write(表达式,0,null)从开始位置替换
//set 列名.write(null,@offset,@length)可以用来删除数据
//set 列名.write(表达式,@offset,@length)只能用于SQL Server2005以上
//set 列名.write(表达式,@offset,@length)用法参考https://www.debugease.com/mssqlbasic/1274092.html
SqlCommand cmdAppend = new SqlCommand("update Files set FileBytes.Write(@FileBytes,null,0) where Id =@id", conn);
cmdAppend.Parameters.AddWithValue("@id", Id);
cmdAppend.Parameters.Add("FileBytes", SqlDbType.VarBinary, bufferLength);
chuk = reader.ReadBytes(bufferLength);
while (chuk.Length > )
{
cmdAppend.Parameters["FileBytes"].Value = chuk;
cmdAppend.ExecuteNonQuery();
chuk = reader.ReadBytes(bufferLength);
}
reader.Close();
}
}
}
文件处理页面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data; namespace WebApplication1
{
/// <summary>
/// FileHandlerLarge 的摘要说明
/// </summary>
public class FileHandlerLarge : IHttpHandler
{
const string connStr = "Data Source=localhost;Initial Catalog=test;Integrated Security=True";
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/msword";
context.Response.Buffer = false;
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select FileBytes from Files where Id =@Id", conn);
cmd.Parameters.AddWithValue("@Id", context.Request["Id"]);
using (conn)
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
if (reader.Read())
{
int bufferSize = ;
byte[] chunk = new byte[bufferSize];
long retCount = ;
long startIndex = ;
//public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length)
//从指定的列偏移量将字节流读入缓冲区,并将其作为从给定的缓冲区偏移量开始的数组。
retCount = reader.GetBytes(, startIndex, chunk, , bufferSize); while (retCount == bufferSize)
{
context.Response.BinaryWrite(chunk);
startIndex += bufferSize;
retCount = reader.GetBytes(, startIndex, chunk, , bufferSize); } //写入最后一个字节数组
byte[] actualChunk = new byte[retCount - ];
Buffer.BlockCopy(chunk, , actualChunk, , (int)retCount - );
context.Response.BinaryWrite(actualChunk);
}
}
context.Response.Write("Hello World");
} public bool IsReusable
{
get
{
return false;
}
}
}
}
C# 上传大文件的更多相关文章
- [Asp.net]Uploadify上传大文件,Http error 404 解决方案
引言 之前使用Uploadify做了一个上传图片并预览的功能,今天在项目中,要使用该插件上传大文件.之前弄过上传图片的demo,就使用该demo进行测试.可以查看我的这篇文章:[Asp.net]Upl ...
- php 上传大文件配置upload_max_filesize和post_max_size选项
php 上传大文件配置upload_max_filesize和post_max_size选项 (2014-04-29 14:42:11) 转载▼ 标签: php.ini upload _files[f ...
- PHP上传大文件 分割文件上传
最近遇到这么个情况,需要将一些大的文件上传到服务器,我现在拥有的权限是只能在一个网页版的文件管理系统来进行操作,可以解压,可以压缩,当然也可以用它来在线编辑.php文件. 文件有40M左右,但是服务器 ...
- ASP.NET上传大文件的问题
原文:http://www.cnblogs.com/wolf-sun/p/3657241.html?utm_source=tuicool&utm_medium=referral 引言 之前使用 ...
- php 上传大文件主要涉及配置upload_max_filesize和post_max_size两个选项
php 上传大文件主要涉及配置 upload_max_filesize 和post_max_size两个选项 今天在做上传的时候出现一个非常怪的问题,有时候表单提交可以获取到值,有时候就获取不到了 ...
- SWFUpload上传大文件(暂时用用,真正用的时候还是要改的)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- PHP上传大文件和处理大数据
1. 上传大文件 /* 以1.5M/秒的速度写入文件,防止一次过写入文件过大导致服务器出错(chy/20150327) */ $is_large_file = false; if( strlen($x ...
- QQ上传大文件为什么这么快
今天和同事在群里讨论“QQ上传大文件/QQ群发送大文件时,可以在极短的时间内完成”是如何做到的. 有时候我们通过QQ上传一个几百M的文件,竟然只用了几秒钟,从带宽上限制可以得出,实际上传文件是不可能的 ...
- IIS7下swfupload上传大文件出现404错误
要求上传附件大小限制在2G,原本以为可以轻松搞定.在编译模式下可以上传大文件,可是在IIS7下(自己架的服务器),一上传大的文件就会出现 Http 404错误,偶尔有的文件还有IO. error错误. ...
- php无法上传大文件完美解决方案
php.ini无法上传大文件完美解决办法 1.打开php.ini(打开方式就不用说了,百度一大堆) 2.查找post_max_size 表单提交最大数值,此项不是限制上传单个文件的大小,而是针对整个表 ...
随机推荐
- [PHP] 浅谈 Laravel Authentication 的 auth:api
auth:api 在 Laravel 的 Routing , Middleware , API Authentication 主题中都有出现. 一. 在 Routing 部分可以知道 auth:api ...
- Winograd Convolution 推导 - 从1D到2D
Winograd Convolution 推导 - 从1D到2D 姚伟峰 http://www.cnblogs.com/Matrix_Yao/ Winograd Convolution 推导 - 从1 ...
- C#中各种Lock的速度比较
简单写了个小程序,比较了一下C#中各种Lock的速度(前提是都没有进入wait状态). 各进入离开Lock 1kw次,结果如下: Lock Time (ms) No lock 58 CriticalS ...
- static示例
求生成对象的个数 class A{ private int i; private static int cnt = 0; //此处用static修饰,让cnt属于类,多个对象共用一个属性,减少内存分配 ...
- threading.local和高级
threading.local特点 ①为每个线程开辟空间,让你进行存取值(根据线程ID来固定某个值) ②flask中没有threading.local,但是flask中的上下文管理的思想是借鉴的thr ...
- day17——序列化、os、sys、hashlib、collections
day17 序列化 json 两组4个方法: 1.dumps(序列化) -- loads(反序列) dumps(list):将对象转换成字符串 loads(str):将字符串转换成对象 list--s ...
- STM32 EV1527无线通信(433)
EV1527无线通信 先说一下这个通信协议的数据格式,这个图片是我在手册里截的. 大家按照单片机类型计算周期,我的是STM32f103vb (4CLK大致等于350um) 发送时按照 先发同步码后发D ...
- java之spring mvc之初始spring mvc
1. mvc : mvc框架是处理 http请求和响应的框架 2. mvc 做的事情有哪些: 将 url 映射到一个java的处理方法上 将表单数据提交到 java 类中 将后台 java 类处理的结 ...
- JavaScript判断是否是正确数值 isNaN
NaN在JavaScript中表示不是数字 JavaScript中isNaN函数方法是返回一个 Boolean 值,指明提供的值是否是保留值 NaN (不是数字). 使用方法:isNaN(numVal ...
- 爬虫多次爬取时候cookie的存储用于登入
一.用requests模块自动保存(保存缓存中) 构建一个session对象session = requests.session() 用构建的session代替requests进行访问他就会自动存啦 ...