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

效果图

上传文件页面:

下载文件页面:
 

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" onclick="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="下载"
onclick="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"/>的值。

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

时间: 2024-08-05 23:18:36

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

Asp.net core 学习笔记 ( upload/download files 文件上传与下载 )

2017-09-25 refer : https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads https://www.codeproject.com/Articles/1203408/Upload-Download-Files-in-ASP-NET-Core 这里只说说小文件上传. 先看看前端 js 代码 <input id="inputFile" type="file" /&g

基于asp.net 的文件上传和下载~~~转

基于asp.net 的文件上传和下载 摘要: 文件的上传和下载是网络中非常重要的两种应用, 本文介绍了使用asp.net 控件实现文件上传的基本方法.解决了当上传大文件时出现各种问题, 并给出了几种解决方案和技巧.另外, 下载文件用二进制读写的方式实现. 1 引言          文件的上传和下载是网络中非常重要的两种应用.其实现方法主要有FTP 方式和HTTP 方式两种, FTP( File Transfer Protocol)是指文件传输协议, 主要用来在网络上传输文件.这种方式虽说文件传

asp.net core系列 69 Amazon S3 资源文件上传示例

原文:asp.net core系列 69 Amazon S3 资源文件上传示例 一.  上传示例 Amazon Simple Storage Service 是互联网存储解决方案.该服务旨在降低开发人员进行网络规模级计算的难度. Amazon S3 提供了一个简单 Web 服务接口,可用于随时在 Web 上的任何位置存储和检索任何数量的数据.此服务让所有开发人员都能访问同一个具备高扩展性.可靠性.安全性和快速价廉的数据存储基础设施, Amazon 用它来运行其全球的网站网络.此服务旨在为开发人员

asp文件上传和下载

ASP.NET实现上传文件 前端 界面十分简单,只是放一个file类型的<input>和一个按钮,并且为这个按钮添加点击事件(btnUpLoad_Click),如下图: 代码: [html] view plain copy <input id="UpLoad" type="file" runat="server" /> <asp:Button runat="server" Text="上

asp.net core文件上传与下载

public class FileController : Controller { /// <summary> /// 跟asp.net webform和asp.net mvc不一样,通过注入的方式,获取项目所在路径 /// </summary> private IHostingEnvironment _hostEnv; public FileController(IHostingEnvironment env) { _hostEnv = env; //其他服务 } public

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

1.使用模型绑定上传文件(官方例子) 官方机器翻译的地址:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads 这里吐槽一下 - -,这TM的机器翻译..还不如自己看E文的.. 首先我们需要创建一个form表单如下: <form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile

利用asp.net正则验证控件验证图片文件格式

<label> 选择图片</label><asp:FileUpload ID="FileUpload1" runat="server" /> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="FileUpload1" D

asp.net.mvc 的单文件上传和多文件上传的简单例子

首先打开vs2012,创建空的mvc4项目,名称为MVCStudy,选择基本模板 1)创建项目后,基本结构是这样的 2)建立对应的HomeController,视图index.fileupload.success.error页面 3)控制器源码 using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.Mvc;using Sys

ASP.NET Core文件上传、下载与删除

首先我们需要创建一个form表单如下: <form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile" asp-action="FileSave"> <div> <div> <p>Form表单多个上传文件:</p> <input type="file"