上传大文件首先要修改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" />&nbsp;
<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# 上传大文件的更多相关文章

  1. [Asp.net]Uploadify上传大文件,Http error 404 解决方案

    引言 之前使用Uploadify做了一个上传图片并预览的功能,今天在项目中,要使用该插件上传大文件.之前弄过上传图片的demo,就使用该demo进行测试.可以查看我的这篇文章:[Asp.net]Upl ...

  2. 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 ...

  3. PHP上传大文件 分割文件上传

    最近遇到这么个情况,需要将一些大的文件上传到服务器,我现在拥有的权限是只能在一个网页版的文件管理系统来进行操作,可以解压,可以压缩,当然也可以用它来在线编辑.php文件. 文件有40M左右,但是服务器 ...

  4. ASP.NET上传大文件的问题

    原文:http://www.cnblogs.com/wolf-sun/p/3657241.html?utm_source=tuicool&utm_medium=referral 引言 之前使用 ...

  5. php 上传大文件主要涉及配置upload_max_filesize和post_max_size两个选项

    php 上传大文件主要涉及配置 upload_max_filesize 和post_max_size两个选项   今天在做上传的时候出现一个非常怪的问题,有时候表单提交可以获取到值,有时候就获取不到了 ...

  6. SWFUpload上传大文件(暂时用用,真正用的时候还是要改的)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. PHP上传大文件和处理大数据

    1. 上传大文件 /* 以1.5M/秒的速度写入文件,防止一次过写入文件过大导致服务器出错(chy/20150327) */ $is_large_file = false; if( strlen($x ...

  8. QQ上传大文件为什么这么快

    今天和同事在群里讨论“QQ上传大文件/QQ群发送大文件时,可以在极短的时间内完成”是如何做到的. 有时候我们通过QQ上传一个几百M的文件,竟然只用了几秒钟,从带宽上限制可以得出,实际上传文件是不可能的 ...

  9. IIS7下swfupload上传大文件出现404错误

    要求上传附件大小限制在2G,原本以为可以轻松搞定.在编译模式下可以上传大文件,可是在IIS7下(自己架的服务器),一上传大的文件就会出现 Http 404错误,偶尔有的文件还有IO. error错误. ...

  10. php无法上传大文件完美解决方案

    php.ini无法上传大文件完美解决办法 1.打开php.ini(打开方式就不用说了,百度一大堆) 2.查找post_max_size 表单提交最大数值,此项不是限制上传单个文件的大小,而是针对整个表 ...

随机推荐

  1. IIS6远程代码执行漏洞复现CVE-2017-7269

    简述 CVE-2017-7269是IIS 6.0中存在的一个栈溢出漏洞,在IIS6.0处理PROPFIND指令的时候,由于对url的长度没有进行有效的长度控制和检查,导致执行memcpy对虚拟路径进行 ...

  2. Python删除文件,空文件夹,非空文件夹

    首先,在Python中文件路径是这种格式: file_path1 = r'F:\test\1' 删除文件,命令 os.remove(file_path1) 删除空文件夹,命令 os.rmdir(fil ...

  3. Python 的语言特性

    谈谈对 Python 和其他语言的区别 Python 是一门语法简洁优美,功能强大无比,应用领域非常广泛,具有强大完备的第三方库,他是一门强类型的可移植.可扩展,可嵌入的解释型编程语言,属于动态语言. ...

  4. spket插件安装并设置JQuery自动提示

    下载地址: com.spket.ui_1.6.23jar包license替换破解.zip: https://pan.baidu.com/s/1JooqlkhHczPT0V34-Qm0oA 提取码: s ...

  5. HTML系列:js和css多种方式实现隔行变色

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. vue中methods、computed、watch区别

    vue中methods.computed.watch区别methods:事件调用的钩子 computed:{ // 计算属性是根据他依赖的值计算的,当依赖值发生变化,其跟着改变 // 计算属性是依赖缓 ...

  7. Spark学习(2) RDD编程

    什么是RDD RDD(Resilient Distributed Dataset)叫做分布式数据集,是Spark中最基本的数据抽象,它代表一个不可变.可分区.弹性.里面的元素可并行计算的集合 RDD允 ...

  8. Keyboarding

    题目描述 思路 一开始想先写一个bfs,目标字符串要加上一个'*',表示这是一个换行符,然后一个字母一个字母的找,每次重置一下vis数组,bfs返回的结果再加上1,表示要打印这个字母,结果第一个样例没 ...

  9. RabbitMQ入门详解以及使用

    目的: RabbitMQ简介 RabbitMQ安装及使用 Centos安装 Docker安装(今天选择Docker安装方法) RabbitMQ快速入门 交换机 RabbitMQ简介 各大主流中间件对比 ...

  10. Django使用distinct报错:DISTINCT ON fields is not supported by this database backend

    具体错误提示是:django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database back ...