拥有网页版小U盘 ASP.NET实现文件上传与下载功能

 更新时间:2021年9月22日 10:07  点击:1769

今天看到了一篇不错的文章,就拿来一起分享一下吧。
实现的是文件的上传与下载功能。

关于文件上传:
谈及文件上传到网站上,首先我们想到的就是通过什么上传呢?在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控件的威力;然而这并不是全部,这里仅仅是冰山一角而已,希望大家继续学习,一起进步一起提高!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • php读取zip文件(删除文件,提取文件,增加文件)实例

    下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • Jupyter Notebook读取csv文件出现的问题及解决

    这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06
  • Photoshop打开PSD文件空白怎么解决

    有时我们接受或下载到的PSD文件打开是空白的,那么我们要如何来解决这个 问题了,下面一聚教程小伙伴就为各位介绍Photoshop打开PSD文件空白解决办法。 1、如我们打开...2016-09-14
  • 在ASP.NET 2.0中操作数据之七十二:调试存储过程

    在开发过程中,使用Visual Studio的断点调试功能可以很方便帮我们调试发现程序存在的错误,同样Visual Studio也支持对SQL Server里面的存储过程进行调试,下面就让我们看看具体的调试方法。...2021-09-22
  • 解决python 使用openpyxl读写大文件的坑

    这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
  • C#实现HTTP下载文件的方法

    这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • C#操作本地文件及保存文件到数据库的基本方法总结

    C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • Php文件上传类class.upload.php用法示例

    本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
  • php批量替换内容或指定目录下所有文件内容

    要替换字符串中的内容我们只要利用php相关函数,如strstr,str_replace,正则表达式了,那么我们要替换目录所有文件的内容就需要先遍历目录再打开文件再利用上面讲的函数替...2016-11-25
  • PHP文件上传一些小收获

    又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
  • jQuery实现简单的文件上传进度条效果

    本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24
  • AI源文件转photoshop图像变模糊问题解决教程

    今天小编在这里就来给photoshop的这一款软件的使用者们来说下AI源文件转photoshop图像变模糊问题的解决教程,各位想知道具体解决方法的使用者们,那么下面就快来跟着小编...2016-09-14
  • js实现上传图片及时预览

    这篇文章主要为大家详细介绍了js实现上传图片及时预览的相关资料,具有一定的参考价值,感兴趣的朋友可以参考一下...2016-05-09
  • C++万能库头文件在vs中的安装步骤(图文)

    这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
  • Zend studio文件注释模板设置方法

    步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
  • php文件上传你必须知道的几点

    本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
  • ant design中upload组件上传大文件,显示进度条进度的实例

    这篇文章主要介绍了ant design中upload组件上传大文件,显示进度条进度的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-29