擁有網頁版小隨身碟 ASP.NET實現檔案上傳與下載功能_實用技巧

來源:互聯網
上載者:User

今天看到了一篇不錯的文章,就拿來一起分享一下吧。
實現的是檔案的上傳與下載功能。

關於檔案上傳:
談及檔案上傳到網站上,首先我們想到的就是通過什麼上傳呢?在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" />           <asp:ImageButton ID="ImageButton_Down" runat="server" OnClick="ImageButton_Down_Click" ToolTip="Download" Width="51px" />    <br />    <br />         <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>   </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" />               <asp:ImageButton ID="ImageButton_Down" runat="server" Height="52px" OnClick="ImageButton_Down_Click" style="margin-top: 0px" ToolTip="Download" Width="107px" />         <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控制項的威力;然而這並不是全部,這裡僅僅是冰山一角而已,希望大家繼續學習,一起進步一起提高!

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.