ASP.NET如何实现文件上传与下载功能
创始人
2024-11-28 09:41:57
0次

关于文件上传:
谈及文件上传到网站上,首先我们想到的就是通过什么上传呢?在ASP.NET中,只需要用FileUpload控件即可完成,但是默认上传4M大小的数据,当然了你可以在web.config文件中进行修改,方式如下:


  

但是这种方式虽然可以自定义文件的大小,但并不是无极限的修改的

下一步,现在“工具”有了,要怎么上传呢?按照直觉是不是应该先选中我想要上传的文件呢?这就对了,因为从FileUpload控件返回后我们便已经得到了在客户端选中的文件的信息了,接下来就是将这个文件进行修改(具体的操作是:去掉所得路径下的盘符的信息,换成服务器上的相关路径下,不过这里并没有更改原本文件的名称)。然后调用相关的上传方法就好了。

先看一下界面文件吧


    
    
    
    
    
    
    
    
       
    
    
    
     
    
 
  

然后是具体的逻辑

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" %>






  


  
    
           
    
       
  
                 
  

 然后是具体的逻辑代码实现

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", "");
      }
    }
  }
  protected void ImageButton_Up_Click(object sender, ImageClickEventArgs e)
  {
    Response.Redirect("Default.aspx");
  }
}

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

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...