今天看到了一篇不错的文章,就拿来一起分享一下吧。

实现的是文件的上传与下载功能。


关于文件上传:

谈及文件上传到网站上,首先我们想到的就是通过什么上传呢?在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" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:ImageButton ID="ImageButton_Down" runat="server" OnClick="ImageButton_Down_Click" ToolTip="Download" Width="51px" />
        <br />
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
&nbsp;
    </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");
    }
}

说完了上传,下面谈一谈文件的下载。这里主要是借助于Directory对象的GetFiles()方法,其可以获得指定路径下的所有的文件的名称。这样我们就可以用之来填充一个listBox,来供我们选择到底要下载那一个文件。

也许这时你会有一点疑惑了,我现在知道了有哪些文件可以下载,那下一步我要怎么来实现呢?

其实这里是利用了Session的存储机制,那就是将我们在listbox 中选择的item的内容记录到session的特定的key中,这样的话,我们就可以不用关心这些信息在页面间是怎么传输的了。只需要在想要进行下载的地方直接获取就可以了。

最为核心的是下载的过程:

if (filepathinfo.Exists)
            {
                //save the file to local
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filepathinfo.Name));
                Response.AddHeader("Content-length", filepathinfo.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.Filter.Close();
                Response.WriteFile(filepathinfo.FullName);
                Response.End();
            }

下面看一下,下载界面的布局文件吧

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ImageButton ID="ImageButton_Up" runat="server" Height="56px" OnClick="ImageButton_Up_Click" ToolTip="Upload" Width="90px" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:ImageButton ID="ImageButton_Down" runat="server" Height="52px" OnClick="ImageButton_Down_Click" style="margin-top: 0px" ToolTip="Download" Width="107px" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <div>

        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Height="169px" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Width="371px"></asp:ListBox>

    </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.IO;

public partial class DownFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)//the first time to load
        {
            //get all the file in File folder
            String[] AllTxt = Directory.GetFiles(Server.MapPath("File"));
            foreach (String name in AllTxt)
            {
                ListBox1.Items.Add(Path.GetFileName(name));
            }
        }
    }
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //make use of sssion to save the selected file in the listbox with the key of "select"
        Session["select"] = ListBox1.SelectedValue.ToString();
    }
    protected void ImageButton_Down_Click(object sender, ImageClickEventArgs e)
    {
        //judge weather user choose at least one file
        if (ListBox1.SelectedValue != "")
        {
            //get the path of the choosed file
            String FilePath = Server.MapPath("File/") + Session["select"].ToString();
            //initial the object of Class FileInfo and make it as the package path
            FileInfo filepathinfo = new FileInfo(FilePath);
            //judge weather the file exists
            if (filepathinfo.Exists)
            {
                //save the file to local
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filepathinfo.Name));
                Response.AddHeader("Content-length", filepathinfo.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.Filter.Close();
                Response.WriteFile(filepathinfo.FullName);
                Response.End();
            }
            else
            {
                Page.RegisterStartupScript("sb", "<script>alert('Please choose one file,sir!')</script>");
            }
        }
    }
    protected void ImageButton_Up_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
}

注意:

最终的上传的文件将会在根目录下的File文件夹下看到,下载的时候也是从这个文件夹下进行下载的。


总结:

经过这个小项目的实践,我看到了session给编程带来的便利,也体会到了FileUpload控件的威力;然而这并不是全部,这里仅仅是冰山一角而已。希望能和广大博友一起进步一起提高!

ASP.NET实现网页版小优盘的更多相关文章

  1. jQuery实践-网页版2048小游戏

    ▓▓▓▓▓▓ 大致介绍 看了一个实现网页版2048小游戏的视频,觉得能做出自己以前喜欢玩的小游戏很有意思便自己动手试了试,真正的验证了这句话-不要以为你以为的就是你以为的,看视频时觉得看懂了,会写了, ...

  2. 分享:计算机图形学期末作业!!利用WebGL的第三方库three.js写一个简单的网页版“我的世界小游戏”

    这几天一直在忙着期末考试,所以一直没有更新我的博客,今天刚把我的期末作业完成了,心情澎湃,所以晚上不管怎么样,我也要写一篇博客纪念一下我上课都没有听,还是通过强大的度娘完成了我的作业的经历.(当然作业 ...

  3. 前端练手小项目——网页版qq音乐仿写

    qq音乐网页版仿写 一些步骤与注意事项 一开始肯定就是html+css布局和页面了,这段特别耗时间,耐心写完就好了 首先要说一下大致流程: 一定要先布局html!,所以一定要先分析页面布局情况,用不同 ...

  4. 微信网页版APP - 网页微信客户端电脑版体验

    微信网页版很早就出来了,解决了很多人上班不能玩手机的问题.微信电脑版-网页微信客户端,直接安装在桌面的微信网页版,免去了开浏览器的麻烦.双击就启动了,和其他的应用程序一样:运行过程中可以隐藏在桌面右下 ...

  5. ASP.NET空网页生成默认代码注释

    当在Visual Studio下生成ASP.NET空网页时,默认生成代码: <%@ Page Language="C#" AutoEventWireup="true ...

  6. 微信收藏导出到PC端的方法,不要再傻傻的用网页版转换了!

    微信里面收藏了很多有意思的东西,想转到PC上保存起来,以防万一哪天链接失效了. 另外PC上面看,屏幕大一些,也爽一些. 以前的方法是需要通过网页版来传输一下,现在微信有了PC客户端,很方便,直接安装P ...

  7. 网页版电子表格控件tmlxSpreadsheet免费下载地址

    tmlxSpreadsheet 是一个由JavaScript 和 PHP 写成的电子表格控件(包含WP插件, Joomla插件等等).. 程序员可以容易的添加一个类似Excel功能的,可编辑的表格功能 ...

  8. 基于html5 canvas和js实现的水果忍者网页版

    今天爱编程小编给大家分享一款基于html5 canvas和js实现的水果忍者网页版. <水果忍者>是一款非常受喜欢的手机游戏,刚看到新闻说<水果忍者>四周年新版要上线了.网页版 ...

  9. 有图有真相,分享一款网页版HTML5飞机射击游戏

    本飞机射击游戏是使用HTML5代码写的,尝试通过统一开发环境(UDE)将游戏托管在MM应用引擎,直接生成了网页版游戏,游戏简单易上手,非常适合用来当做小休闲打发时间. 游戏地址:http://flyg ...

随机推荐

  1. Servlet中service()方法

    在学习Servlet的过程中,我们大多时候编码都是直接继承HttpServlet这个类,并且重写doGet ,doPost,但是查看Api时我们会发现Servlet接口 ,GenericSevlet抽 ...

  2. 再谈RunLoop

    RunLoop 一 概述: 一句话解释RunLoop:运行任务的循环. 为什么要有RunLoop:解决交互式UI设计中的一个问题,如何快速响应用户输入,如何快速将程序运行结果输出到屏幕? 计算机是个笨 ...

  3. ACM 排列2

    Ray又对数字的列产生了兴趣: 现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数.  Input每组数据占一行,代表四张卡片上的数字(0<=数字<=9 ...

  4. Go 语言类型转换

    类型转换用于将一种数据类型的变量转换为另外一种类型的变量.Go 语言类型转换基本格式如下: type_name(expression) type_name 为类型,expression 为表达式. 实 ...

  5. MongoDB 连接

    启动 MongoDB服务 在前面的教程中,我们已经讨论了如何启动MongoDB服务,你只需要在MongoDB安装目录的bin目录下执行'mongod'即可. 执行启动操作后,mongodb在输出一些必 ...

  6. Docker常见仓库MySQL

    MySQL 基本信息 MySQL 是开源的关系数据库实现. 该仓库提供了 MySQL 各个版本的镜像,包括 5.6 系列.5.7 系列等. 使用方法 默认会在 3306 端口启动数据库. $ sudo ...

  7. Xcode在playground的quick look框中显示对象自定义视图

    对于一般对象,playground中默认的quick look显示已经够用,比如简单的字符串,Int,或简单的自定义Class等等. 不过对于有些情况,我们需要自定义对象在playground中的显示 ...

  8. Retrofit2.0+RxJava+Dragger2实现不一样的Android网络架构搭建

    Tamic :csdn http://blog.csdn.net/sk719887916 众所周知,手机APP的核心就在于调用后台接口,展示相关信息,方便我们在手机上就能和外界交互.所以APP中网络框 ...

  9. Oracle11g R2创建PASSWORD_VERIFY_FUNCTION对应密码复杂度验证函数步骤

    Oracle11g R2创建PASSWORD_VERIFY_FUNCTION对应密码复杂度验证函数步骤 运行测试环境:数据库服务器Oracle Linux 5.8 + Oracle 11g R2数据库 ...

  10. C++ 中const作用

    一.对const与#define的特点及区别的理解 #define只是用来做文本替换的,#define常量的生命周期止于编译期,它存在于程序的代码段,在实际程序中它只是一个常数,一个命令中的参数,并没 ...