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 表单提交最大数值,此项不是限制上传单个文件的大小,而是针对整个表 ...
随机推荐
- Android最新版本号与API级别对应关系
Android版本号与API级别对应关系表 名称 版本号 API等级 发布时间 BuildVersion 2012-11-01 BuildVersionCodes.JellyBeanMr1 Jell ...
- 解决net core mvc 中文乱码问题
在Startup 配置文件下的ConfigureServices方法中添加: services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All ...
- ThinkPHP3(结构,路由,模板的调用,后台搭建,系统常量)
ThinkPHP的结构如下: 在ThinkPHP\Library\Think文件夹中,几个重要的文件 1.App.class.php 框架核心类文件 2.Think.class.php 每次请求都要执 ...
- 【剑指offer】1+….+n,不能使用相关关键字
题目描述 求1+2+3+...+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C). 分析:可以使用递归! class Soluti ...
- 17 SpringMVC response响应
1.Model.ModelMap和ModelAndView的使用详解 Spring-MVC在请求处理方法可出现和返回的参数类型中,最重要就是Model和ModelAndView了,对于MVC框架,控制 ...
- nginx+upsync+consul 构建动态nginx配置系统
参考: http://www.php230.com/weixin1456193048.html [upsync模块说明.性能评测] https://www.jianshu.com/p/76352ef ...
- Django框架之第五篇(模板层) --变量、过滤器、标签、自定义标签、过滤器,模板的继承、模板的注入、静态文件
模板层 模板层就是html页面,Django系统中的(template) 一.视图层给模板传值的两种方法 方式一:通过键值对的形式传参,指名道姓的传参 n = 'xxx'f = 'yyy'return ...
- 远程登录Linux系统(使用xshell),远程上传加载文件(使用Xftp)
一.Xshell(远程登录Linux系统) 1.安装xshell 自己百度找安装包 2.连接登录 1.连接前提 需要Linux开启一个sshd的服务,监听22号端口,一般默认是开启的 查看是否开启: ...
- pytest_01-环境准备与入门
前言 首先说下为什么要学pytest,在此之前相信大家已经掌握了python里面的unittest单元测试框架,那再学一个框架肯定是需要学习时间成本的. 刚开始我的内心是拒绝的,我想我用unittes ...
- 女性对DeepNude脱衣技术的防护
写在前面的话 本文不提供下载方式,开源部分只是社区逆向后公开的部分源码 这篇文章有些人看了可能会比较极端,但不从技术角度分析又谈何防护?攻与防一直存在,不管是安全还是AI都是一样 你极端不极端,它就在 ...