It has a small U disk ASP. NET to realize file uploading and downloading functions
- 2021-08-12 02:36:47
- OfStack
Today, I saw a good article, so let's share it with one.
It realizes the function of uploading and downloading files.
About file uploading:
When it comes to uploading files to websites, the first thing we think of is through what upload? In ASP. NET, you only need FileUpload control to complete, but the default upload 4M size data, of course, you can modify in web. config file, as follows:
<system.web>
<httpRuntime executionTimeout="240"
maxRequestLength="20480"/>
</system.web>
However, although this method can customize the file size, it is not unlimited modification
The next step, now that the "tool" is available, how to upload it? Should I intuitively select the file I want to upload first? That's right, because after returning from FileUpload control, we have already got the information of the file selected in the client, and the next step is to modify this file (the specific operation is to remove the information of the drive letter under the obtained path and replace it with the relevant path on the server, but the name of the original file has not been changed here). Then call the relevant upload method.
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" ToolTip="Download" Width="51px" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Then there is 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 uploading, let's talk about downloading files. This is mainly with the help of the GetFiles () method of the Directory object, which can obtain the names of all files under the specified path. So we can use it to populate an listBox, so that we can choose which file to download.
Maybe at this time you will have a doubt, I now know what files can be downloaded, then the next step I want to achieve?
In fact, the storage mechanism of Session is used here, that is, the contents of item selected in listbox are recorded in the specific key of session, so that we don't have to care about how this information is transmitted between pages. Just get it directly where you want to download it.
The core is the download process:
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();
}
Look at 1 below and download the layout file of the interface
<%@ 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>
Then it is 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 (!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");
}
}
Note:
The final uploaded file will be seen in the File folder under the root directory, and the download will also be downloaded from this folder.
Summary:
Through the practice of this small project, I saw the convenience brought by session to programming, and also realized the power of FileUpload control; However, this is not all, here is just the tip of the iceberg. I hope everyone will continue to learn and make progress and improve!