今天看到了一篇不错的文章,就拿来一起分享一下吧。
实现的是文件的上传与下载功能。
关于文件上传:
谈及文件上传到网站上,首先我们想到的就是通过什么上传呢?在ASP.NET中,只需要用FileUpload控件即可完成,但是默认上传4M大小的数据,当然了你可以在web.config文件中进行修改,方式如下:
<system.web>
<httpRuntime executionTimeout="240"
maxRequestLength="20480"/>
</system.web>
但是这种方式虽然可以自定义文件的大小,但并不是无极限的修改的
下一步,现在“工具”有了,要怎么上传呢?按照直觉是不是应该先选中我想要上传的文件呢?这就对了,因为从FileUpload控件返回后我们便已经得到了在客户端选中的文件的信息了,接下来就是将这个文件进行修改(具体的操作是:去掉所得路径下的盘符的信息,换成服务器上的相关路径下,不过这里并没有更改原本文件的名称)。然后调用相关的上传方法就好了。
先看一下界面文件吧
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:ImageButton ID="ImageButton_Up" runat="server" OnClick="ImageButton_Up_Click" style="text-decoration: underline" ToolTip="Up" Width="54px" />
<asp:ImageButton ID="ImageButton_Down" runat="server" OnClick="ImageButton_Down_Click" ToolTip="Download" Width="51px" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
然后是具体的逻辑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//a method for currying file updown
private void UpFile()
{
String strFileName;
//get the path of the file
String FilePath = Server.MapPath("./") + "File";
//judge weather has file to upload
if (FileUpload1.PostedFile.FileName != null)
{
strFileName = FileUpload1.PostedFile.FileName;
//save all the message of the file
strFileName = strFileName.Substring(strFileName.LastIndexOf("") + 1);
try
{
FileUpload1.SaveAs(FilePath + "" + this.FileUpload1.FileName);
//save the file and obey the rules
Label1.Text = "Upload success!";
}
catch (Exception e)
{
Label1.Text = "Upload Failed!"+e.Message.ToString();
}
}
}
protected void ImageButton_Up_Click(object sender, ImageClickEventArgs e)
{
UpFile();
}
protected void ImageButton_Down_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("DownFile.aspx");
}
}








