当前位置:Gxlcms > asp.net > 拥有网页版小U盘 ASP.NET实现文件上传与下载功能

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

时间:2021-07-01 10:21:17 帮助过:12人阅读

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

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

  1. <system.web>
  2. <httpRuntime executionTimeout="240"
  3. maxRequestLength="20480"/>
  4. </system.web>

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

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

先看一下界面文件吧

  1. <form id="form1" runat="server">
  2. <asp:FileUpload ID="FileUpload1" runat="server" />
  3. <br />
  4. <br />
  5. <br />
  6. <br />
  7. <br />
  8. <br />
  9. <asp:ImageButton ID="ImageButton_Up" runat="server" OnClick="ImageButton_Up_Click" style="text-decoration: underline" ToolTip="Up" Width="54px" />
  10.        
  11. <asp:ImageButton ID="ImageButton_Down" runat="server" OnClick="ImageButton_Down_Click" ToolTip="Download" Width="51px" />
  12. <br />
  13. <br />
  14.      
  15. <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
  16.  
  17. </form>

然后是具体的逻辑

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. public partial class _Default : System.Web.UI.Page
  8. {
  9. protected void Page_Load(object sender, EventArgs e)
  10. {
  11. }
  12. //a method for currying file updown
  13. private void UpFile()
  14. {
  15. String strFileName;
  16. //get the path of the file
  17. String FilePath = Server.MapPath("./") + "File";
  18. //judge weather has file to upload
  19. if (FileUpload1.PostedFile.FileName != null)
  20. {
  21. strFileName = FileUpload1.PostedFile.FileName;
  22. //save all the message of the file
  23. strFileName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
  24. try
  25. {
  26. FileUpload1.SaveAs(FilePath + "\\" + this.FileUpload1.FileName);
  27. //save the file and obey the rules
  28. Label1.Text = "Upload success!";
  29. }
  30. catch (Exception e)
  31. {
  32. Label1.Text = "Upload Failed!"+e.Message.ToString();
  33. }
  34. }
  35. }
  36. protected void ImageButton_Up_Click(object sender, ImageClickEventArgs e)
  37. {
  38. UpFile();
  39. }
  40. protected void ImageButton_Down_Click(object sender, ImageClickEventArgs e)
  41. {
  42. Response.Redirect("DownFile.aspx");
  43. }
  44. }

说完了上传,下面谈一谈文件的下载。这里主要是借助于Directory对象的GetFiles()方法,其可以获得指定路径下的所有的文件的名称。这样我们就可以用之来填充一个listBox,来供我们选择到底要下载那一个文件。
也许这时你会有一点疑惑了,我现在知道了有哪些文件可以下载,那下一步我要怎么来实现呢?
其实这里是利用了Session的存储机制,那就是将我们在listbox 中选择的item的内容记录到session的特定的key中,这样的话,我们就可以不用关心这些信息在页面间是怎么传输的了。只需要在想要进行下载的地方直接获取就可以了。
最为核心的是下载的过程:

  1. if (filepathinfo.Exists)
  2. {
  3. //save the file to local
  4. Response.Clear();
  5. Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filepathinfo.Name));
  6. Response.AddHeader("Content-length", filepathinfo.Length.ToString());
  7. Response.ContentType = "application/octet-stream";
  8. Response.Filter.Close();
  9. Response.WriteFile(filepathinfo.FullName);
  10. Response.End();
  11. }

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

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DownFile.aspx.cs" Inherits="DownFile" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  6. <title></title>
  7. </head>
  8. <body>
  9. <form id="form1" runat="server">
  10. <asp:ImageButton ID="ImageButton_Up" runat="server" Height="56px" OnClick="ImageButton_Up_Click" ToolTip="Upload" Width="90px" />
  11.            
  12. <asp:ImageButton ID="ImageButton_Down" runat="server" Height="52px" OnClick="ImageButton_Down_Click" style="margin-top: 0px" ToolTip="Download" Width="107px" />
  13.        
  14. <div>
  15. <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
  16. <br />
  17. <asp:ListBox ID="ListBox1" runat="server" Height="169px" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Width="371px"></asp:ListBox>
  18. </div>
  19. </form>
  20. </body>
  21. </html>

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.IO;
  8. public partial class DownFile : System.Web.UI.Page
  9. {
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. if (!Page.IsPostBack)//the first time to load
  13. {
  14. //get all the file in File folder
  15. String[] AllTxt = Directory.GetFiles(Server.MapPath("File"));
  16. foreach (String name in AllTxt)
  17. {
  18. ListBox1.Items.Add(Path.GetFileName(name));
  19. }
  20. }
  21. }
  22. protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
  23. {
  24. //make use of sssion to save the selected file in the listbox with the key of "select"
  25. Session["select"] = ListBox1.SelectedValue.ToString();
  26. }
  27. protected void ImageButton_Down_Click(object sender, ImageClickEventArgs e)
  28. {
  29. //judge weather user choose at least one file
  30. if (ListBox1.SelectedValue != "")
  31. {
  32. //get the path of the choosed file
  33. String FilePath = Server.MapPath("File/") + Session["select"].ToString();
  34. //initial the object of Class FileInfo and make it as the package path
  35. FileInfo filepathinfo = new FileInfo(FilePath);
  36. //judge weather the file exists
  37. if (filepathinfo.Exists)
  38. {
  39. //save the file to local
  40. Response.Clear();
  41. Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filepathinfo.Name));
  42. Response.AddHeader("Content-length", filepathinfo.Length.ToString());
  43. Response.ContentType = "application/octet-stream";
  44. Response.Filter.Close();
  45. Response.WriteFile(filepathinfo.FullName);
  46. Response.End();
  47. }
  48. else
  49. {
  50. Page.RegisterStartupScript("sb", "<script>alert('Please choose one file,sir!')</script>");
  51. }
  52. }
  53. }
  54. protected void ImageButton_Up_Click(object sender, ImageClickEventArgs e)
  55. {
  56. Response.Redirect("Default.aspx");
  57. }
  58. }

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

总结:
经过这个小项目的实践,我看到了session给编程带来的便利,也体会到了FileUpload控件的威力;然而这并不是全部,这里仅仅是冰山一角而已,希望大家继续学习,一起进步一起提高!

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

人气教程排行