Have a web version of the small U disk ASP. NET implementation of File upload and download function _ Practical skills

Source: Internet
Author: User
Tags file upload urlencode

Today, I saw a good article, let's share it.
The implementation is the file upload and download function.

about file uploads:
Referring to the file uploaded to the site, the first thing we think of is through what upload it? In asp.net, you only need to use the FileUpload control to complete, but the default upload 4M size of data, of course, you can modify the Web.config file, the following way:

<system.web>
   
 

But this way, although the size of the file can be customized, but not without the limit of the modified

Next, now the "tool" has, how to upload it? Should I choose the file I want to upload first, according to my intuition? That's right, because we've got the information of the file selected at the client after returning from the FileUpload control, and the next step is to modify the file (the specific action is: To remove the information of the disk in the resulting path and replace it with the relevant path on the server). However, the name of the original file is not changed here. And then call the relevant upload method just fine.

Let's look at the interface file first.

<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" to oltip= "Download" width= "51px"/> <br/> <br/> <asp:label id=
    "Label1" runat= " Server "text=" Label ></asp:Label>
  </form>

Then it's the concrete logic.

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")
  ;

 }
}

After saying the upload, let's talk about downloading the files . This is primarily through the directory object's GetFiles () method , which gets the names of all the files under the specified path. So we can use it to populate a ListBox for us to choose exactly which file to download.
Perhaps at this time you will be a little puzzled, I now know what files can be downloaded, then how do I do it next?
In fact, this is the use of the session of the storage mechanism, that is, we selected in the ListBox in the contents of the item recorded to the session of the specific key, so that we can not care about how the information in the page is how the transmission. Just get it right where you want to download it.
The most core is the process of downloading:

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 ();
      }


Let's look at the layout file for the download interface.

<%@ Page language= "C #" autoeventwireup= "true" codefile= "DownFile.aspx.cs" inherits= "Downfile"%> <! DOCTYPE html>  

Then it's the concrete Logic code implementation

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 (!p Age. IsPostBack)//the-i-load {//get All "file in file folder string[] Alltxt = Directory.getfil
      ES (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 Sav
  E 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 Lea
St 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 ");

 }
}

Attention:
The final uploaded files will be seen in the file folder under the root directory and downloaded from this folder.

Summarize:
After this small project practice, I saw the session to the programming to bring the convenience, also realized the FileUpload control the power; but this is not all, here is only the tip of the iceberg, I hope you continue to learn, together with progress to improve together!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.