ASP.NET實現文件上傳和下載
1、搭建網站結構
2、編寫網頁文件
創建一個Web窗體UploadFile和UpFile文件夾,UploadFile包含UploadFile.aspx和UploadFile.aspx.cs兩個文件,源代碼如下:
[UploadFile.aspx]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadFile.aspx.cs" Inherits="WebForrmDemo.UploadFile" %>
<!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">
<div>
請選擇要上傳的文件:<asp:FileUpload ID="fileup" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="開始上傳" OnClick="btnUpload_Click"/>
<br />
<asp:Literal ID="lblMsg" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
[UploadFile.aspx.cs]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace WebForrmDemo
{
public partial class UploadFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//【1】判斷文件是否存在
if (fileup.HasFile)
{
//【2】獲取文件的大小,判斷是否符合設置要求
//1mb=1024kb
//1kb=1024byte
double fileLength=fileup.FileContent.Length / (1024.0 * 1024.0);
//獲取配置文件中上傳文件大小的限制
double limitLength = Convert.ToDouble(ConfigurationManager.AppSettings["fileMaxLength"])/1024.0;
if (fileLength>limitLength)
{
lblMsg.Text = $"上傳文件不能超過{limitLength}MB";
return;
}
//【3】獲取文件名,判斷文件擴展名是否符合要求
string fileName = fileup.FileName;
//判斷文件是否是exe文件,則不能上傳
if (fileName.Substring(fileName.LastIndexOf(".")).ToLower()==".exe")
{
lblMsg.Text = "不能上傳應用程序";
return;
}
//【4】修改文件名稱
//一般情況下,上傳的文件服務器中保存時不會採取原文件名,因爲客戶端用戶是非常龐大的,所以要保證每個客戶端上傳的文件不能被覆蓋
fileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + "_" + fileName;
//【5】獲取服務器中存儲文件的路徑
//"~"代表應用程序的根目錄,從服務器的根目錄尋找
string path = Server.MapPath("~/UPFile");
//【6】上傳文件
try
{
fileup.SaveAs(path+"/"+fileName);
lblMsg.Text = "文件上傳成功!";
}
catch (Exception ex)
{
lblMsg.Text = $"文件上傳失敗:{ex.Message}";
}
}
}
}
}
3.在Web.config加入下面代碼:
<appSettings>
<!--配置上傳文件最大字節數爲30mb:單位kb-->
<add key="fileMaxLength" value="30720"/>
</appSettings>
<system.web>
<!--httpRuntime中可以設置請求的最大字節數-->
<httpRuntime targetFramework="4.6.1" maxRequestLength="40960"/>
</system.web>
4、運行測試
(1) 點擊選擇文件
(2) 確定好文件
(3)點擊上傳,顯示文件上傳成功。
(4)在程序的目錄下面可以看到剛纔上傳的文件