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 表单提交最大数值,此项不是限制上传单个文件的大小,而是针对整个表 ...
随机推荐
- 晶体管放大电路与Multisim仿真学习笔记
前言 开始写点博客记录学习的点滴,第一篇就写基本的共射极放大电路吧. 很多教材都是偏重理论,而铃木雅臣著作的<晶体管电路设计>是一本很实用的书籍,个人十分推荐! 下面开始我的模电重温之旅吧 ...
- 小甲鱼汇编语言学习笔记——day03
手动编译并执行第一个汇编程序过程: 1.用notepad++写一个简单的汇编程序(文件命名为:1.asm): assume cs:abc abc segment mov ax, 2 add ax, a ...
- [bug]——vue 组件状态外置引发的一个 bug
背景 在编写 .vue 组件时,可以将状态外置来获取一些额外的好处,譬如有这么一个组件(global-components.vue): <template> <div> < ...
- SpringBoot中使用Thymeleaf模板
1.引入pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId& ...
- A记录(主机名解析)、CNAME(别名解析)和URL转发(域名转发)
什么是 A记录(主机名解析).CNAME(别名解析)和URL转发(域名转发)? A记录(主机名解析)是最普通的域名解析,是把某一主机名解析到一个IP. 例如www.***.com-> 20.10 ...
- 关于于c++中的类型转换
隐藏式类型转换 void test() { ; ; a = b; //此时发生的是默认的类型转 //(据说编译器是微软的编译器是不允许编译通过) std::cout << a <&l ...
- DELPHI6中DSGNINTF.DCU找不到时的解决方法
https://www.cnblogs.com/gaodu2003/archive/2009/06/04/1495789.html 1.添加 lib\designide.dcp到控件的dpk文件的re ...
- 【C语言】崩溃的双重指针
指针的指针? 前言: 指针的初识点击移步 双重指针: 指向指针的指针是一种多级间接寻址的形式,或者说是一个指针链.通常,一个指针包含一个变量的地址.当我们定义一个指向指针的指针时,第一个指针包含了第二 ...
- Tcl语言学习--基础知识
一.脚本.命令和单词符号 一个TCL脚本可以包含一个或多个命令.命令之间必须用换行符或分号隔开. 1.关键字/变量 变量是程序的基础变量组成:变量名.变量值变量名要求:任何字符串都可以作为变量名,区分 ...
- RabbitMQ之消息模式(下)
目的: RabbitMQ之消息模式(上):https://www.cnblogs.com/huangting/p/11994539.html 消费端限流 消息的ACK与重回队列 TTL消息 死信队列 ...