效果图

上传文件页面:

下载文件页面:
 

1、母版页site.Master

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="upAndDown.SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form runat="server">
<div class="page">
<div class="header">
<div class="title">
<h1>
我的 ASP.NET 应用程序之-多文件上传+超大附件上传
</h1>
</div>
<div class="loginDisplay">
-by Leon</div>
<div class="clear hideSkiplink">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" 
EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal" 
>
<Items>
<asp:MenuItem NavigateUrl="~/Default.aspx" Text="上传"/>
<asp:MenuItem NavigateUrl="~/Download.aspx" Text="下载"/>
</Items>
</asp:Menu>
</div>
</div>
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
</div>
<div class="clear">
</div>
</div>
<div class="footer">
</div>
</form>
</body>
</html>

2、Default.aspx 上传页面

<%@ Page Title="文件上传与下载" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="upAndDown._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
上传文件到服务器</h2>
<h2>
<asp:FileUpload ID="FileUpload1" runat="server" />
</h2>
<p>
<asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="上传" style="margin-left:170px;" />
</p>
</asp:Content>

3、Default.aspx.cs 
using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace upAndDown
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public Boolean UpLoad(string path, FileUpload fileupload) 
{
bool fileOK = false;
if(fileupload.HasFile)
{
string fileException = System.IO.Path.GetExtension(fileupload.FileName).ToLower();
//上传文件的格式
string[] allowedException = {".xls",".doc",".mp3",".rar",".zip",".vsd",".txt",".jpg",".gif",".bmp"
,".png",".swf",".avi",".mp3",".rm",".wma",".wmv",".exe"};
for (int i = 0; i < allowedException.Length;i++ ) 
{
if (fileException == allowedException[i]) 
fileOK = true;  //返回成功标识
}
}
if (fileOK)     //判断上传的文件是否在指定的格式范围之内
{
//判断文件是否存在,如不存在则创建路径
if (System.IO.Directory.Exists(path))
{
//该目录存在,则将上传的文件保存在该目录当中
}
else
{
System.IO.Directory.CreateDirectory(path);      //创建文件路径
}
fileupload.SaveAs(path + "\\" + fileupload.FileName.Trim().Replace(" ",""));   //去掉文件名字符空格,执行文件上传操作
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "name", "<script>alert('文件上传成功!')</script>");
}
else 
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert('hehh')", "<script>alert('不支持此格式文件上传!')</script>");
}
return fileOK;
}
protected void Button1_Click(object sender, EventArgs e)
{
string FilePath = "";
//是否有上传文件
if (this.FileUpload1.FileName != null && this.FileUpload1.FileName != "")
{
if (FileUpload1.PostedFile.ContentLength <= 0)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert('hehh')", "<script>alert('上传文件为空文件,请重新选择!')</script>"); 
return;
}
else
if (this.FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentLength > 524288000)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "<script>alert('上传文件过大!')</script>"); 
return;
}
else
{
FilePath = Server.MapPath("/Images"); //设置服务器路径
}
UpLoad(FilePath, this.FileUpload1);//调用UpLoad()函数上传文件
}
}
}
//如果上传文件错误,则返回操作
else 
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "name", "<script>alert('文件为空,请先选择要上传的文件!')</script>"); 
return;
}
}
}
}


4、Download.aspx 下载页面

<%@ Page Title="文件下载" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Download.aspx.cs" Inherits="upAndDown.Download" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2 style="font-size: xx-large">
从服务器上下载文件</h2>
<p>
<asp:ListBox ID="ListBox1" runat="server" Height="249px"  Width="541px">
</asp:ListBox>
</p>
<embed style="filter: xray()" src="Images/GEM.mp3" width="188" height="68" type="audio/mp3"
loop="true" showstatusbar="true" autostart="true"/>
<p>
<asp:Button ID="Button1" runat="server" Font-Bold="True" Font-Size="Small" Font-Strikeout="False" Text="下载" οnclick="Button1_Click" />
</p>
</asp:Content>

5、Download.aspx.cs

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace upAndDown
{
public partial class Download : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
//页面加载时,获取下载文件的存放目录
string strfilepath = Server.MapPath("~/Images/");
//创建目录对象
DirectoryInfo dir = new DirectoryInfo(strfilepath);
//获得该目录下的所有文件
FileSystemInfo[] files = dir.GetFileSystemInfos();
//讲遍历的文件名称显示在ListBox控件中
ListItem items;
foreach (FileSystemInfo infofiles in files) 
{
items = new ListItem();        //声明一个ListItem对象
items.Text = infofiles.Name;
items.Value = infofiles.FullName;
ListBox1.Items.Add(items);     //向ListBox控件中添加数据信息
}
}
}
//<summary>
//文件下载函数
//</summary>
//author Leon
//<param name="fileURL">要下载文件所在的路径</param>
protected Boolean DownLoad(string fileURL)
{
Boolean Dok = false;
try
{
string FullPathURL = Server.MapPath(fileURL);//获取文件下载路径
System.IO.FileInfo file = new System.IO.FileInfo(FullPathURL);
if (file.Exists)        //判断要下载的文件是否存在
{
Response.Clear();       //清空response对象中的内容
//*修改前的做法
Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name);
//*修改后的做法
Response.AddHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(file.Name));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(FullPathURL);      //通过对Response对象执行下载文件的操作
Response.End();     //结束Response对象
Response.Flush();       //刷新Response对象
Response.Clear();       //清空response对象中的内容
Dok = true;
}
else
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"success","<script>alert(' 文件不存在!')</script>");
}
}
catch (Exception)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "success", "<script>alert('文件不存在!')</script>");
}
return Dok;
}
protected void Button1_Click(object sender, EventArgs e)
{
//获取下载文件的路径
string downfiles;
try
{
downfiles = "Images/" + ListBox1.SelectedItem.Text;
DownLoad(downfiles);
}
catch (Exception)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "success", "<script>alert('选择文件为空,请先选择要下载的文件!')</script>");
}
}
}
}

注:ASP.NET框架默认最大上传文件为4M,如果要修改框架默认最大上传文件大小, 需要到C:\Windows \Microsoft.NET\Framework\v4.0.30319\Config文件夹中修改machine.config文件, 在<system.web> 标签中加入或修改<httpRuntime maxRequestLength="4096000"/>的值。

转载于:https://www.cnblogs.com/leon719/p/3862568.html

2014-07-23 利用ASP.NET自带控件实现单文件上传与下载相关推荐

  1. asp.net web常用控件FileUpload(文件上传控件)

    2019独角兽企业重金招聘Python工程师标准>>> FileUpload控件的主要中能:向指定目录上传文件,该控件包括一个文本框和一个浏览按钮. 常用的属性:FileBytes, ...

  2. 利用ASP.NET2.0向导控件一步步建立与用户的交互--------提高和自定义用户体验

    本文是利用ASP.NET2.0向导控件一步步建立与用户的交互--------基本概念的后续文章,介绍了Wizard控件的高级使用以提高用户使用体验. 单击下面链接进行查看 http://www.cnm ...

  3. asp.net 文件上传和下载管理源码

    利用asp.net进行文件上传和下载时非常常用的功能,现做整理,将源码上传,提供给初学者参考,以下代码中的样式文件就不上传了,下载者请将样式去掉. 效果图如下: <%@ Page Languag ...

  4. [转载]ASP.NET Core文件上传与下载(多种上传方式)

    ASP.NET Core文件上传与下载(多种上传方式) 前言 前段时间项目上线,实在太忙,最近终于开始可以研究研究ASP.NET Core了. 打算写个系列,但是还没想好目录,今天先来一篇,后面在整理 ...

  5. Asp.net MVC 1.0 RTM中实现文件上传

    Asp.net MVC 1.0 RTM中实现文件上传 在我们开始之前,你需要知道一个form以post方式上传文件的方式,你将要增加一个特别的enctype attribute到form标签上,为了这 ...

  6. ASP.NET 文件上传于下载

    本文主要介绍一下,在APS.NET中文件的简单上传于下载,上传是将文件上传到服务器的指定目录下,下载是从存入数据库中的路径,从服务器上下载. 1.上传文件 (1)页面代码 <table alig ...

  7. ASP.NET MVC实现简单的文件上传与下载

    使用ASP.NET MVC实现简单的文件上传与下载. 1.上传文件HTML <form action='@Url.Action("Upload", "File&qu ...

  8. asp.net coree文件上传与下载实例

    asp.net core像springboot非常相似,我们从一个springboot文件上传与下载的例子来引到asp.net core的文件上传与下载: 本文asp.net core版本为:6.0 ...

  9. ASP.NET文件上传和下载

    大学最近作出相关的需求进行上传和下载文件的网站(求为:站点发布的通知,在后台要能给每一个通知加入附件.在前台要能显示并下载附件),之前仅仅是学习过关于上传的 理论知识,这里实践了一下下,与大家分享一下 ...

最新文章

  1. python开发的软件sparrow-sparrow
  2. IOS开发中常量的处理
  3. server2003进入oracle,windows server 2003安装oracle
  4. sqlserver 存储过程 增加
  5. mysql怎么插入10w测试数据_mysql快速插入100万测试数据
  6. PyQt5 Pyinstaller时出现错误Cannot find PyQt5 plugin directories
  7. 小米10首销战绩公布:嘴上说不买身体却很诚实
  8. tomcat系列之项目下载中文文件乱码问题
  9. 用vue做一个简单的emoji表情组件
  10. 【揭秘Wintel提升win 7系统性能的背后】
  11. 无线局域网和蜂窝移动网络_干货!无线AP覆盖系统解决方案
  12. SO-Pose: Exploiting Self-Occlusion for Direct 6D Pose Estimation
  13. -D指定db登陆失败ERROR 1044 (42000): Access denied for user ‘lzldb‘@‘%‘ to database ‘lzldb‘
  14. 最新 lineageos 编译过程 详细过程
  15. 力扣-股票的资本损益
  16. 数据结构与算法基础Day1
  17. Comet OJ 夏季欢乐赛 Gree的心房
  18. 积累的力量(《把时间当作朋友》读书笔记)
  19. Matlab使用串口进行数据通信
  20. 培训班出身的程序员,和科班程序员有什么区别?

热门文章

  1. 数据库集群的级联复制完整实现
  2. Log4j自定义Appender介绍
  3. IOS之--UI进阶--多控制器管理第一天
  4. linux -- /dev/null 21
  5. 模拟grub损坏及丢失
  6. C++11中正則表達式測试
  7. oracle 10g 用户管理笔记
  8. 三层交换机原理解析(转)
  9. 三星二级菜单_你变我也变,神奇的excel二级联动下拉菜单
  10. Mysql —— C语言链接mysql数据库,命令行形式(getopt()函数),用户、用户组增删改查(用户组表内有用户控制的策略字段)