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

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

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

效果图如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUploadManager.aspx.cs"
    Inherits="NewsManagement_FileUploadManager" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>文件上传管理</title>
    <link href="../themes/common.css" rel="stylesheet" type="text/css" />
    <link href="../themes/reset.css" rel="stylesheet" type="text/css" />
    <link href="../themes/modules.css" rel="stylesheet" type="text/css" />
    <link href="../themes/fix.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div class="right">
        <table cellpadding="1" cellspacing="1" class="tablesingle" width="100%" style=" height:500px;">
            <tr>
                <td colspan="3">
                    <asp:Label ID="lab_FolderInfo" runat="server" Font-Size="Medium"></asp:Label>
                </td>
            </tr>
            <tr>
                <td class="tablesingletdlable"  valign="top" align="center">
                    允许上传文件的类型:
                    <asp:BulletedList ID="bl_FileTypeLimit" runat="server">
                    </asp:BulletedList>
                    允许上传单个文件的大小:
                    <asp:Label ID="lab_FileSizeLimit" runat="server" Text=""></asp:Label>
                </td>
                <td class="tablesingletdlable" align="left">
                    <asp:FileUpload ID="FileUpload" runat="server" Width="300px" /><br /><br />
                    <asp:Button ID="btn_Upload" runat="server" CssClass="button-add-new" Style="height: 26px;
                        width: 64px; border: 0px;" Text="上传文件" OnClick="btn_Upload_Click" />
                </td>
                <td class="tablesingletdlable">
                    <table cellpadding="1" cellspacing="1" class="tablesingle" width="100%">
                        <tr>
                            <td>
                                <!--启用了AutoPostBack-->
                                <asp:ListBox ID="lb_FileList" runat="server" AutoPostBack="True" Width="300px" Height="400px"
                                    OnSelectedIndexChanged="lb_FileList_SelectedIndexChanged"></asp:ListBox>
                            </td>
                            <td valign="top">
                                <asp:Label ID="lab_FileDescription" runat="server" Text=""></asp:Label>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <asp:Button ID="btn_Download" runat="server" CssClass="button-add-new" Style="height: 26px;
            width: 64px; border: 0px;" Text="下载文件" OnClick="btn_Download_Click" /> 
                                <!--在删除前给予确认-->
                                <asp:Button ID="btn_Delete" runat="server" CssClass="button-add-new" Style="height: 26px;
            width: 64px; border: 0px;" Text="删除文件" OnClientClick="return confirm('确定删除文件吗?')"
                                    OnClick="btn_Delete_Click" /><br />
                                <asp:TextBox ID="tb_FileNewName" runat="server" Width="300px"></asp:TextBox> 
                                <asp:Button ID="btn_Rename" runat="server" CssClass="button-4" Style="height: 26px;
            width: 110px; border: 0px;" Text="对文件重命名" OnClick="btn_Rename_Click" /> 
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Configuration;
using SYIT.Tools.DotNetUI;

public partial class NewsManagement_FileUploadManager : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //防止PostBack后列表信息重复添加
        if (!IsPostBack)
        {
            //初始化文件夹信息
            InitFolderInfo();
            //初始化上传限制信息
            InitUploadLimit();
            //初始化文件列表
            InitFileList();
        }
    }

    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        //判断用户是否选择了文件
        if (FileUpload.HasFile)
        {
            //调用自定义方法判断文件类型是否符合要求
            if (IsAllowableFileType())
            {
                //调用自定义方法判断文件大小是否符合要求
                if (IsAllowableFileSize())
                {
                    //从config中读取文件上传路径
                    string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
                    //从UploadFile中读取文件名
                    string strFileName = FileUpload.FileName;
                    //组合成物理路径
                    string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
                    //保存文件
                    FileUpload.SaveAs(strFilePhysicalPath);
                    //更新文件列表框控件
                    lb_FileList.Items.Add(strFileName);
                    //更新文件夹信息
                    InitFolderInfo();
                    //调用自定义方法显示提示
                    ShowMsgHelper.AlertMsg2("文件成功上传!");
                    //ShowMessageBox("文件成功上传");
                }
                else
                {
                    //调用自定义方法显示提示
                    
                    ShowMessageBox("文件大小不符合要求,请参看上传限制");
                }
            }
            else
            {
                //调用自定义方法显示提示
               
                ShowMessageBox("文件类型不符合要求,请参看上传限制");
            }
        }
        else
        {
            //调用自定义方法显示提示
           
            ShowMessageBox("请选择一个文件");
        }
    }

    protected void btn_Download_Click(object sender, EventArgs e)
    {
        //从config中读取文件上传路径
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //从列表框控件中读取选择的文件名
        string strFileName = lb_FileList.SelectedValue;
        //组合成物理路径
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //清空输出流
        Response.Clear();
        //在HTTP头中加入文件名信息
        Response.AddHeader("Content-Disposition", "attachment;FileName=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));
        //定义输出流MIME类型为
        Response.ContentType = "application/octet-stream";
        //从磁盘读取文件流
        System.IO.FileStream fs = System.IO.File.OpenRead(strFilePhysicalPath);
        //定义缓冲区大小
        byte[] buffer = new byte[102400];
        //第一次读取
        int i = fs.Read(buffer, 0, buffer.Length);
        //如果读取的字节大于0,则使用BinaryWrite()不断向客户端输出文件流
        while (i > 0)
        {
            Response.BinaryWrite(buffer);
            i = fs.Read(buffer, 0, buffer.Length);
        }
        //关闭磁盘文件流
        fs.Close();
        //关闭输出流
        Response.End();
    }

    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        //从config中读取文件上传路径
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //从列表框控件中读取选择的文件名
        string strFileName = lb_FileList.SelectedValue;
        //组合成物理路径
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //删除文件
        System.IO.File.Delete(strFilePhysicalPath);
        //更新文件列表框控件
        lb_FileList.Items.Remove(lb_FileList.Items.FindByText(strFileName));
        //更新文件夹信息
        InitFolderInfo();
        //更新文件描述信息
        tb_FileNewName.Text = "";
        //更新重命名文本框
        lab_FileDescription.Text = "";
        //调用自定义方法显示提示
      
        ShowMessageBox("文件成功删除");
    }

    protected void btn_Rename_Click(object sender, EventArgs e)
    {
        //从config中读取文件上传路径
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //从列表框控件中读取选择的文件名
        string strFileName = lb_FileList.SelectedValue;
        //从重命名文本框中读取新文件名
        string strFileNewName = tb_FileNewName.Text;
        //组合成物理路径
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //组合成物理路径
        string strFileNewPhysicalPath = Server.MapPath(strFileUploadPath + strFileNewName);
        //文件重命名
        System.IO.File.Move(strFilePhysicalPath, strFileNewPhysicalPath);
        //找到文件列表框控件中的匹配项
        ListItem li = lb_FileList.Items.FindByText(strFileName);
        //修改文字
        li.Text = strFileNewName;
        //修改值
        li.Value = strFileNewName;
        //调用自定义方法显示提示
       
        ShowMessageBox("文件成功重命名");
    }

    protected void lb_FileList_SelectedIndexChanged(object sender, EventArgs e)
    {
        //从config中读取文件上传路径
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //从列表框控件中读取选择的文件名
        string strFileName = lb_FileList.SelectedValue;
        //组合成物理路径
        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
        //根据物理路径实例化文件信息类
        FileInfo fi = new FileInfo(strFilePhysicalPath);
        //获得文件大小和创建时间并赋值给标签
        lab_FileDescription.Text = string.Format("文件大小:{0} 字节<br><br>上传时间:{1}<br>", fi.Length, fi.CreationTime);
        //把文件名赋值给重命名文本框
        tb_FileNewName.Text = strFileName;
    }

    private void InitFolderInfo()
    {
        //从config中读取文件上传路径
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //判断上传文件夹是否存在
        if (!Directory.Exists(Server.MapPath(strFileUploadPath)))
            Directory.CreateDirectory(Server.MapPath(strFileUploadPath));
        //组合成物理路径
        string strFilePath = Server.MapPath(strFileUploadPath);
        //从config中读取文件夹容量限制
        double iFolderSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FolderSizeLimit"]);
        //声明表示文件夹已用空间的变量并赋初始值
        double iFolderCurrentSize = 0;
        //获取文件夹中所有文件
        FileInfo[] arrFiles = new DirectoryInfo(strFilePath).GetFiles();
        //累加文件大小获得已用空间值
        foreach (FileInfo fi in arrFiles)
            iFolderCurrentSize += Convert.ToInt32(fi.Length / 1024);
        //把文件夹容量和已用空间信息赋值给标签
        lab_FolderInfo.Text = string.Format("文件夹容量限制:{0} M 已用空间:{1:f2} M", iFolderSizeLimit / 1024, iFolderCurrentSize / 1024);
    }

    private void InitUploadLimit()
    {
        //从config中读取上传文件类型限制并根据逗号分割成字符串数组
        string[] arrFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString().Split(',');
        //从config中读取上传文件大小限制
        double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]);
        //遍历字符串数组把所有项加入项目编号控件
        for (int i = 0; i < arrFileTypeLimit.Length; i++)
            bl_FileTypeLimit.Items.Add(arrFileTypeLimit[i].ToString());
        //把文件大小限制赋值给标签
        lab_FileSizeLimit.Text = string.Format("{0:f2} M", iFileSizeLimit / 1024);
    }

    private void InitFileList()
    {
        //从config中读取文件上传路径
        string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
        //组合成物理路径
        string strFilePath = Server.MapPath(strFileUploadPath);
        //读取文件夹下所有文件
        FileInfo[] arrFiles = new DirectoryInfo(strFilePath).GetFiles();
        //把文件名逐一添加到列表框控件控件
        foreach (FileInfo fi in arrFiles)
            lb_FileList.Items.Add(fi.Name);
    }

    private bool IsAllowableFileSize()
    {
        //从config中读取上传文件大小限制
        double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;
        //文件大小是否超出了大小限制?
        if (iFileSizeLimit > FileUpload.PostedFile.ContentLength)
            return true;
        else
            return false;
    }

    private bool IsAllowableFileType()
    {
        //从config中读取上传文件类型限制
        string strFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString();
        //当前文件扩展名是否能在这个字符串中找到?
        if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUpload.FileName).ToLower()) > -1)
            return true;
        else
            return false;
    }

    private void ShowMessageBox(string strMessaage)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", string.Format("<script>alert('{0}')</script>", strMessaage));
    }
}

===========================================================================

如果觉得对您有帮助,微信扫一扫支持一下:


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
相关文章
|
存储 开发框架 前端开发
前端框架EXT.NET Dotnet 3.5开发的实验室信息管理系统(LIMS)成品源码 B/S架构
发展历史:实验室信息管理系统(LIMS),就是指通过计算机网络技术对实验的各种信息进行管理的计算机软、硬件系统。也就是将计算机网络技术与现代的管理思想有机结合,利用数据处理技术、海量数据存储技术、宽带传输网络技术、自动化仪器分析技术,来对实验室的信息管理和质量控制等进行全方位管理的计算机软、硬件系统,以满足实验室管理上的各种目标(计划、控制、执行)。
227 1
|
6月前
|
C++ Windows
.NET Framework安装不成功,下载`NET Framework 3.5`文件,Microsoft Visual C++
.NET Framework常见问题及解决方案汇总,涵盖缺失组件、安装失败、错误代码等,提供多种修复方法,包括全能王DLL修复工具、微软官方运行库及命令行安装等,适用于Windows系统,解决应用程序无法运行问题。
941 3
|
3月前
|
开发框架 安全 .NET
Microsoft .NET Framework 3.5、4.5.2、4.8.1,适用于 Windows 版本的 .NET,Microsoft C Runtime等下载
.NET Framework是Windows平台的开发框架,包含CLR和FCL,支持多种语言开发桌面、Web应用。常用版本有3.5、4.5.2、4.8.1,系统可同时安装多个版本,确保软件兼容运行。
860 0
Microsoft .NET Framework 3.5、4.5.2、4.8.1,适用于 Windows 版本的 .NET,Microsoft C Runtime等下载
|
5月前
.NET Framework 3.5离线安装包合集下载
本文介绍了如何获取和安装.NET Framework运行库离线合集包。用户可通过提供的链接下载安装包,安装过程简单,按提示逐步操作即可完成。安装时可选择所需版本,工具会自动适配架构,无需手动判断,方便高效。
4432 0
|
10月前
|
存储 XML 开发工具
【Azure Storage Account】利用App Service作为反向代理, 并使用.NET Storage Account SDK实现上传/下载操作
本文介绍了如何在Azure上使用App Service作为反向代理,以自定义域名访问Storage Account。主要内容包括: 1. **设置反向代理**:通过配置`applicationhost.xdt`和`web.config`文件,启用IIS代理功能并设置重写规则。 2. **验证访问**:测试原生URL和自定义域名的访问效果,确保两者均可正常访问Storage Account。 3. **.NET SDK连接**:使用共享访问签名(SAS URL)初始化BlobServiceClient对象,实现通过自定义域名访问存储服务。
173 1
|
开发框架 前端开发 .NET
LIMS(实验室)信息管理系统源码、有哪些应用领域?采用C# ASP.NET dotnet 3.5 开发的一套实验室信息系统源码
集成于VS 2019,EXT.NET前端和ASP.NET后端,搭配MSSQL 2018数据库。系统覆盖样品管理、数据分析、报表和项目管理等实验室全流程。应用广泛,包括生产质检(如石化、制药)、环保监测、试验研究等领域。随着技术发展,现代LIMS还融合了临床、电子实验室笔记本和SaaS等功能,以满足复杂多样的实验室管理需求。
281 3
LIMS(实验室)信息管理系统源码、有哪些应用领域?采用C# ASP.NET dotnet 3.5 开发的一套实验室信息系统源码
一款.NET开源、跨平台的DASH/HLS/MSS下载工具
一款.NET开源、跨平台的DASH/HLS/MSS下载工具
201 1
|
Web App开发 开发框架 .NET
ASP淘特二手房房地产系统源码
ASP淘特二手房房地产系统源码主要提供了房屋信息出售、出租、求购、求租、合租等信息的发布平台。 本系统已提供成熟的赢利模式,通过向中介会员提供发布信息平台收取会员费为网站的主要收入来源,中介会员申请开通后,可以添加经济人和管理中介公司所属的房源信息。可在线续费购买服务期(支付宝接口)、购买置顶等。
233 2
效率提升利器:一个在线的.NET源码查询网站
效率提升利器:一个在线的.NET源码查询网站
189 0
|
安全 程序员 Shell
老程序员分享:NSIS自定义界面,下载并安装Net.Framework4.8
老程序员分享:NSIS自定义界面,下载并安装Net.Framework4.8