惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

博客园 - 月异星邪

Anaconda官方网站下载慢的解决方法 定时任务调度自动提醒企业微信 天高云淡 leobbs皮肤 - 月异星邪 - 博客园 仿QQ信息弹出 - 月异星邪 - 博客园 http://www.xywq.com/files/ganzhi11.htm IIS6 Http压缩配置方法 - 月异星邪 - 博客园 IIS6,SESSION超时时间过短的解决(未测试) 如何实现函数IF的嵌套超过七层? 常用asp.net代码 - 月异星邪 - 博客园 在ASP.NET中使用Session常见问题集锦 ASP.NET 2.0:使用用户控件和定制的Web部件个人化你的门户网站 ASP.NET中常用的文件上传下载方法 Infragistics中WebGrid的MultiColumn Headers设计 轻松实现UltraWebGrid中的分页控制 http://www.bo-blog.com/index.php?l=zh_tw&mod=skins ASP.NET 2.0中使用webpart系列控件 ASP.NET2.0 WebPart实例教程 数字转换为大写人民币(附源码) 用ASP.NET 2.0实现AJAX风格的Web开发
ASP.NET中常用的文件上传下载方法
月异星邪 · 2007-01-05 · via 博客园 - 月异星邪

ASP.NET中常用的文件上传下载方法     文件的上传下载是我们在实际项目开发过程中经常需要用到的技术,这里给出几种常见的方法,本文主要内容包括:
1、如何解决文件上传大小的限制
2、以文件形式保存到服务器
3、转换成二进制字节流保存到数据库以及下载方法
4、上传Internet上的资源

第一部分:

    首先我们来说一下如何解决ASP.NET中的文件上传大小限制的问题,我们知道在默认情况下ASP.NET的文件上传大小限制为2M,一般情况下,我们可以采用更改WEB.Config文件来自定义最大文件大小,如下:

<httpRuntime executionTimeout="300" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/>

这样上传文件的最大值就变成了4M,但这样并不能让我们无限的扩大MaxRequestLength的值,因为ASP.NET会将全部文件载入内存后,再加以处理。解决的方法是利用隐含的HttpWorkerRequest,用它的GetPreloadedEntityBody和ReadEntityBody方法从IIS为ASP.NET建立的pipe里分块读取数据。实现方法如下:

IServiceProvider provider=(IServiceProvider) HttpContext.Current;
HttpWorkerRequest wr=(HttpWorkerRequest) provider.GetService(typeof(HttpWorkerRequest));
byte[]bs=wr.GetPreloadedEntityBody();
.
if(!wr.IsEntireEntityBodyIsPreloaded())
{
intn=1024;
byte[]bs2=newbyte[n];
while(wr.ReadEntityBody(bs2,n)>0)
{
..
}
}

这样就可以解决了大文件的上传问题了。

第二部分:

    下面我们来介绍如何以文件形式将客户端的一个文件上传到服务器并返回上传文件的一些基本信息
首先我们定义一个类,用来存储上传的文件的信息(返回时需要)。

public class FileUpLoad
{
public FileUpLoad()
{
}
/// <summary>
        public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
private string fileName;
/// <summary>
        public string FilePath
{
get
{
return filepath;
}
set
{
filepath = value;
}
}
private string filepath;
/// <summary>
        public string FileExtension
{
get
{
return fileExtension;
}
set
{
fileExtension = value;
}
}
private string fileExtension;
}

另外我们还可以在配置文件中限制上传文件的格式

<?xml version="1.0" encoding="gb2312" ?>
<Application>
<FileUpLoad>
<Format>.jpg|.gif|.png|.bmp</Format>
</FileUpLoad>
</Application>

这样我们就可以开始写我们的上传文件的方法了,如下:

public FileUpLoad UpLoadFile(HtmlInputFile InputFile,string filePath,string myfileName,bool isRandom)
{
FileUpLoad fp = new FileUpLoad();
string fileName,fileExtension;
string saveName;
            HttpPostedFile postedFile = InputFile.PostedFile;
fileName        = System.IO.Path.GetFileName(postedFile.FileName);
fileExtension    = System.IO.Path.GetExtension(fileName);
            AppConfig app = new AppConfig();
string format = app.GetPath("FileUpLoad/Format");
            if(format.IndexOf(fileExtension)==-1)
{
throw new ApplicationException("上传数据格式不合法");
}
            if(myfileName != string.Empty)
{
fileName = myfileName;
}
if(isRandom)
{
Random objRand = new Random();
System.DateTime date = DateTime.Now;
                saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString()
+ date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);
fileName = saveName + fileExtension;
}
string phyPath = HttpContext.Current.Request.MapPath(filePath);
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
if(!upDir.Exists)
{
upDir.Create();
}
            try
{
postedFile.SaveAs(phyPath + fileName);
fp.FilePath =  filePath  + fileName;
fp.FileExtension = fileExtension;
fp.FileName = fileName;
}
catch
{
throw new ApplicationException("上传失败!");
}
            return fp;
}

然后我们在上传文件的时候就可以调用这个方法了,将返回的文件信息保存到数据库中,至于下载,就直接打开那个路径就OK了。

第三部分:

    这里我们主要说一下如何以二进制的形式上传文件以及下载。首先说上传,方法如下:

public byte[] UpLoadFile(HtmlInputFile f_IFile)
{
         HttpPostedFile upFile=f_IFile.PostedFile;
                int upFileLength=upFile.ContentLength;
                string contentType = upFile.ContentType;
byte[] FileArray=new Byte[upFileLength];
Stream fileStream=upFile.InputStream;
fileStream.Read(FileArray,0,upFileLength);
return FileArray;
}

这个方法返回的就是上传的文件的二进制字节流,这样我们就可以将它保存到数据库了。下面说一下这种形式的下载,也许你会想到这种方式的下载就是新建一个aspx页面,然后在它的Page_Load()事件里取出二进制字节流,然后再读出来就可以了,其实这种方法是不可取的,在实际的运用中也许会出现无法打开某站点的错误,我一般采用下面的方法:
首先,在Web.config中加入:

<add verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/>

这表示我打开openfile.aspx这个页面时,系统就会自动转到执行RuixinOA.Web.BaseClass.OpenFile 这个类里的方法,具体实现如下:

using System;
using System.Data;
using System.Web;
using System.IO;
using Ruixin.WorkFlowDB;
using RXSuite.Base;
using RXSuite.Component;
using RuixinOA.BusinessFacade;
namespace RuixinOA.Web.BaseClass
{
/// <summary>
    public class OpenFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
            RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
EntityData data = os.GetFileDetail(id);
if(data != null && data.Tables["RX_OA_File"].Rows.Count > 0)
{
DataRow dr = (DataRow)data.Tables["RX_OA_File"].Rows[0];
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = dr["CContentType"].ToString();
context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
context.Response.BinaryWrite((Byte[])dr["CContent"]);
context.Response.Flush();
context.Response.End();
}
}
public bool IsReusable
{
get { return true;}
}
}
}

执行上面的方法后,系统会提示用户选择直接打开还是下载。这一部分我们就说到这里。

第四部分:

    这一部分主要说如何上传一个Internet上的资源到服务器。前面我们有一篇文章详细介绍了使用方法,这里我不再多说。
请参考:将动态页面转化成二进制字节流 

第五部分:总结
    今天简单的介绍了几种文件上传与下载的方法,都是在实际的项目开发中经常需要用到的,可能还有不完善的地方,希望大家可以互相交流一下项目开发中的经验。写的不好的地方,请指正,谢谢!