当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net文件上传示例分享

asp.net文件上传示例分享

2017年12月12日  | 移动技术网IT编程  | 我要评论

薄 熙 来,大润发是哪个国家的,天福茗茶

方法一:用web控件fileupload,上传到网站根目录。

test.aspx关键代码:

复制代码 代码如下:

<form id="form1" runat="server">
<asp:fileupload id="fileupload1" runat="server" />
<asp:button id="button1" runat="server" text="上传" onclick="button1_click" />
<asp:label id="label1" runat="server" text="" style="color: red"></asp:label>
</form>

test.aspx.cs关键代码:

复制代码 代码如下:

protected void button1_click(object sender, eventargs e)
{
    if (fileupload1.hasfile)
    {
    fileupload1.saveas(server.mappath("~/") + fileupload1.filename);
    label1.text = "上传成功!";
    }
}

方法二:用html控件htmlinputfile,上传到网站根目录。

test.aspx关键代码:
 

复制代码 代码如下:

<form id="form1" runat="server">
<input type="file" id="file1" runat="server" />
<asp:button id="button1" runat="server" text="上传" onclick="button1_click" />
<asp:label id="label1" runat="server" text="" style="color: red"></asp:label>
</form>

test.aspx.cs关键代码:

复制代码 代码如下:

protected void button1_click(object sender, eventargs e)
{
    if (file1.postedfile.contentlength > 0)
    {
    file1.postedfile.saveas(server.mappath("~/") + path.getfilename(file1.postedfile.filename));
    label1.text = "上传成功!";
    }
}

方法三:用html元素<input type="file" …/>,通过request.files上传到网站根目录。

test.aspx关键代码:

复制代码 代码如下:

<form id="form1" runat="server" enctype="multipart/form-data">
<input type="file" name="file" />
<asp:button id="button1" runat="server" text="上传" onclick="button1_click" />
<asp:label id="label1" runat="server" text="" style="color: red"></asp:label>
</form>

test.aspx.cs关键代码:
 

复制代码 代码如下:

protected void button1_click(object sender, eventargs e)
{
    if (request.files["file"].contentlength > 0)
    {
    request.files["file"].saveas(server.mappath("~/") + path.getfilename(request.files["file"].filename));
    label1.text = "上传成功!";
    }
}

注意两个区别:

一:fileupload.filename获取客户端上传文件名(不带路径),而file1.postedfile.filename 和request.files["file"].filename在不同浏览器下情况不同:ie8下获得的是客户端上传文件的完全限定名(带路径),谷歌、苹果等浏览器下则仍为文件名(不带路径)。

二:fileupload控件有hasfile属性,用于判断用户是否选择了上传文件,而后面两种方法则需要通过判断上传文件大小contentlength属性,当用户没有选择上传文件时,该属性值为0。

可以看出fileupload封装程度更高,但灵活性也稍差。

例,asp.net 文件上传类(取得文件后缀名,保存文件,加入文字水印)

复制代码 代码如下:

using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.drawing;
using system.io;
using system.drawing.imaging;

namespace ec
{
/// <summary>
/// 上传类
/// </summary>
public class uploadobj
{

public uploadobj()
{
//
// todo: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 允许文件上传的类型枚举
/// </summary>
public enum filetype
{
jpg,gif,bmp,png
}

#region 取得文件后缀
/// <summary>
/// 取得文件后缀
/// </summary>
/// <param name="filename">文件名称</param>
/// <returns></returns>
public static string getfileextends(string filename)
{
string ext = null;
if (filename.indexof('.') > 0)
{
string[] fs = filename.split('.');
ext = fs[fs.length - 1];
}
return ext;
}
#endregion

#region 检测文件是否合法
/// <summary>
/// 检测上传文件是否合法
/// </summary>
/// <param name="fileextends">文件后缀名</param>
/// <returns></returns>
public static bool checkfileextends(string fileextends)
{
bool status = false;
fileextends = fileextends.tolower();
string[] fe = enum.getnames(typeof(filetype));
for (int i = 0; i < fe.length; i++)
{
if (fe[i].tolower() == fileextends)
{
status = true;
break;
}
}
return status;
}
#endregion

#region 保存文件
/// <summary>
/// 保存文件
/// </summary>
/// <param name="fpath">全路径,server.mappath()</param>
/// <param name="myfileupload">上传控件</param>
/// <returns></returns>
public static string photosave(string fpath,fileupload myfileupload)
{
string s = "";
string fileextends = "";
string filename = myfileupload.filename;
if (filename != "")
{
//取得文件后缀
fileextends = ec.uploadobj.getfileextends(filename);
if (!ec.uploadobj.checkfileextends(fileextends))
{
ec.messageobject.showpre("上传文件类型不合法");
}
random rd = new random();
s = ec.randomobject.daterndname(rd) + "." + fileextends;
string file = fpath + "\" + s;
try
{
myfileupload.saveas(file);
}
catch (exception ee)
{
throw new exception(ee.tostring());
}
}
return s;
}

#endregion

#region 加入文字水印

/// <summary>
/// 加入文字水印
/// </summary>
/// <param name="filename">文件名称路径(全路径)</param>
/// <param name="text">文件</param>
public void addtexttoimg(string filename, string text)
{
if (!file.exists(filename))
{
throw new filenotfoundexception("文件不存在");
}
if (text == string.empty)
{
return;
}

system.drawing.image image = system.drawing.image.fromfile(filename);
bitmap bitmap = new bitmap(image, image.width, image.height);
graphics g = graphics.fromimage(bitmap);
float fontsize = 12.0f;//字体大小
float textwidth = text.length * fontsize;//文本的长度
//下面定义一个矩形区域,以后在这个矩形里面画上白底黑字
float rectx = 0;
float recty = 0;
float rectwidth = text.length * (fontsize + 8);
float rectheight = fontsize + 8;
//声明矩形域
rectanglef textarea = new rectanglef(rectx, recty, rectwidth, rectheight);
font font = new font("宋体", fontsize);//定义字体
brush whitebrush = new solidbrush(color.white);//白笔刷,画文字用
brush blackbrush = new solidbrush(color.black);//黑笔刷,画背景用
g.fillrectangle(blackbrush, rectx, recty, rectwidth, rectheight);
g.drawstring(text, font, whitebrush, textarea);
memorystream ms = new memorystream();
bitmap.save(ms, imageformat.jpeg);
//输出处理后的图像,这里为了演示方便,我将图片显示在页面中了
//response.clear();
//response.contenttype = "image/jpeg";
//response.binarywrite(ms.toarray());
g.dispose();
bitmap.dispose();
image.dispose();
}
#endregion
}
}

asp.net的弊端

asp.net处理文件上传的最大的问题在于内存占用太高,由于将整个文件载入内存进行处理,导致如果用户上传文件太大,或者同时上传的用户太多,会造成服务器端内存耗尽。这个观点其实是片面的,对于早期asp.net 1.x,为了供程序处理,会将用户上传的内容完全载入内存,这的确会带来问题,但在asp.net 2.0中就已经会在用户上传数据超过一定数量之后将其存在硬盘中的临时文件中,而这点对于开发人员完全透明,也就是说,开发人员可以像以前一样进行数据流的处理,这个也在httpruntime里通过
requestlengthdiskthreshold 属性来设置阈值(threshold),其默认值为256,即一个请求内容超过256kb时就会启用硬盘作为缓存,这个阈值和客户端是否是在上传内容无关,只关心客户端发来的请求大于这个值。因此,在asp.net 2.0中服务器的内存不会因为客户端的异常请求而耗尽。另外一个弊端就是当请求超过maxrequestlength(默认4m)之后,asp.net处理程序将不会处理该请求。这和asp.net抛出一个异常完全不同,这就是为什么如果用户上传文件太大,看到的并不是asp.net应用程序中指定的错误页面(或者默认的),因为asp.net还没有对这个请求进行处理。

还有一个问题就是处理asp.net大文件上传的超时。这个其实可以通过在运行时读取web.config中的httpruntime节,并转化为 httpruntimesection对象或者重写page.onerror()来检测http code(相应代码)是否为400来处理,这里不再赘述

代码如下:

复制代码 代码如下:

    system.configuration.configuration  
    config = webconfigurationmanager. 
    openwebconfiguration("~"); 
    httpruntimesection section = config.getsection 
    ("system.web/httpruntime") as httpruntimesection; 
    double maxfilesize = math.round 
    (section.maxrequestlength / 1024.0, 1); 
    string errorstring = string.format("make sure  
    your file is under {0:0.#} mb.", maxfilesize);

    protected override void onerror(eventargs e) 
    { 
    httpcontext ctx = httpcontext.current; 
    exception exception = ctx.server.getlasterror (); 

    string errorstring =  
"
    offending url: " + ctx.request.url.tostring () + 
"
    source: " + exception.source +  
"
    message: " + exception.message + 
"
    stack trace: " + exception.stacktrace; 

    ctx.response.write (errorstring); 

    ctx.server.clearerror (); 

    base.onerror (e); 
    }


对于文件上传的功能需要较为特别的需求——例如进度条提示,asp.net封装的控件〈asp:fileupload /〉就无能为力了。

好的解决方案

robert bazinet建议,最好的解决方案是使用ria,大多数情况下,建议用silverlight或 flash的上传组件来替代传统的fileupload组件,这类组件不只是提供了更好的上传体验,也比〈input type="file"〉标签在页面上的文本框、按钮漂亮,这个〈input type="file"〉标签并不能够通过css添加样式,不过也有人尝试去解决了。至今为止并没有什么商业上传组件使用了silverlight,不过这里有演示了用silverlight进行多文件上传的示例程序。当然使用silverlight就可以很轻松的实现多线程上传,断点续传这种功能了,这些都不是我要详细讨论的内容,如果有需要可以自己去看下。

可选择的解决方案

使用〈input type="file" /〉标签所能提供的支持非常有限,一些特殊需求我们不能实现——或者说是无法轻易地、直接地实现。所以为了实现这样的功能我们每次都要绕一个大大的弯。为了避免每次实现相同功能时都要费神费时地走一遍弯路,市面上或者开源界出现了各种上传组件,上传组件提供了封装好的功能,使得我们在实现文件上传功能时变得轻松了很多。例如几乎所有的上传组件都直接或间接地提供了进度提示的功能,有的提供了当前的百分比数值,有的则直接提供了一套ui;有的组件只提供了简单的ui,有的却提供了一整套上传、删除的管理界面。此外,有的组件还提供了防止客户端恶意上传的能力。

我觉得最好的办法是在httpmodule里分块读取文件并且保持页面激活的状态,这样就不会超时,同时也可以跟踪进度或者取消上传,或者通过 httphandler实现,在通过进度条给用户充分提示的同时,也让开发人员能够更好地控制文件大小以及上传过程中可能出现的异常。上传组件都是用这些办法的,我们的选择有:

fileuploader.net (mediachase公司,$310以上)  
radupload (telerik公司,$249)  
neatupload (免费,遵守lgpl协议) 

neatupload是在asp.net pipeline的beginrequest事件中截获当前的httpworkerrequest对象,然后直接调用其readentitybody等方法获取客户端传递过来的数据流,并加以分析和处理。并通过使用新的请求进行轮询来获取当前上传的状态。关于neatupload和其他开源组件的介绍可以参看jeffreyzhao的在asp.net应用程序中上传文件,当然他还说了memba velodoc xp edition和swfupload,写的非常棒!

httpworkerrequest实现介绍

利用隐含的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()) 

int n=1024; 
byte[] bs2=new byte[n]; 
while(wr.readentitybody(bs2,n) 〉0) 


}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网