利用asp.net進行文件上傳和下載時非常常用的功能,現做整理,將源碼上傳,提供給初學者參考,以下代碼中的樣式文件就不上傳了,下載者請將樣式去掉。
效果圖如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUploadManager.aspx.cs"
Inherits="NewsManagement_FileUploadManager" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>文件上傳管理</title>
<link href="../themes/common.css" rel="stylesheet" type="text/css" />
<link href="../themes/reset.css" rel="stylesheet" type="text/css" />
<link href="../themes/modules.css" rel="stylesheet" type="text/css" />
<link href="../themes/fix.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div class="right">
<table cellpadding="1" cellspacing="1" class="tablesingle" width="100%" style=" height:500px;">
<tr>
<td colspan="3">
<asp:Label ID="lab_FolderInfo" runat="server" Font-Size="Medium"></asp:Label>
</td>
</tr>
<tr>
<td class="tablesingletdlable" valign="top" align="center">
允許上傳文件的類型:
<asp:BulletedList ID="bl_FileTypeLimit" runat="server">
</asp:BulletedList>
允許上傳單個文件的大小:
<asp:Label ID="lab_FileSizeLimit" runat="server" Text=""></asp:Label>
</td>
<td class="tablesingletdlable" align="left">
<asp:FileUpload ID="FileUpload" runat="server" Width="300px" /><br /><br />
<asp:Button ID="btn_Upload" runat="server" CssClass="button-add-new" Style="height: 26px;
width: 64px; border: 0px;" Text="上傳文件" OnClick="btn_Upload_Click" />
</td>
<td class="tablesingletdlable">
<table cellpadding="1" cellspacing="1" class="tablesingle" width="100%">
<tr>
<td>
<!--啓用了AutoPostBack-->
<asp:ListBox ID="lb_FileList" runat="server" AutoPostBack="True" Width="300px" Height="400px"
OnSelectedIndexChanged="lb_FileList_SelectedIndexChanged"></asp:ListBox>
</td>
<td valign="top">
<asp:Label ID="lab_FileDescription" runat="server" Text=""></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btn_Download" runat="server" CssClass="button-add-new" Style="height: 26px;
width: 64px; border: 0px;" Text="下載文件" OnClick="btn_Download_Click" />
<!--在刪除前給予確認-->
<asp:Button ID="btn_Delete" runat="server" CssClass="button-add-new" Style="height: 26px;
width: 64px; border: 0px;" Text="刪除文件" OnClientClick="return confirm('確定刪除文件嗎?')"
OnClick="btn_Delete_Click" /><br />
<asp:TextBox ID="tb_FileNewName" runat="server" Width="300px"></asp:TextBox>
<asp:Button ID="btn_Rename" runat="server" CssClass="button-4" Style="height: 26px;
width: 110px; border: 0px;" Text="對文件重命名" OnClick="btn_Rename_Click" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</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.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Configuration;
using SYIT.Tools.DotNetUI;
public partial class NewsManagement_FileUploadManager : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//防止PostBack後列表信息重複添加
if (!IsPostBack)
{
//初始化文件夾信息
InitFolderInfo();
//初始化上傳限制信息
InitUploadLimit();
//初始化文件列表
InitFileList();
}
}
protected void btn_Upload_Click(object sender, EventArgs e)
{
//判斷用戶是否選擇了文件
if (FileUpload.HasFile)
{
//調用自定義方法判斷文件類型是否符合要求
if (IsAllowableFileType())
{
//調用自定義方法判斷文件大小是否符合要求
if (IsAllowableFileSize())
{
//從config中讀取文件上傳路徑
string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
//從UploadFile中讀取文件名
string strFileName = FileUpload.FileName;
//組合成物理路徑
string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
//保存文件
FileUpload.SaveAs(strFilePhysicalPath);
//更新文件列表框控件
lb_FileList.Items.Add(strFileName);
//更新文件夾信息
InitFolderInfo();
//調用自定義方法顯示提示
ShowMsgHelper.AlertMsg2("文件成功上傳!");
//ShowMessageBox("文件成功上傳");
}
else
{
//調用自定義方法顯示提示
ShowMessageBox("文件大小不符合要求,請參看上傳限制");
}
}
else
{
//調用自定義方法顯示提示
ShowMessageBox("文件類型不符合要求,請參看上傳限制");
}
}
else
{
//調用自定義方法顯示提示
ShowMessageBox("請選擇一個文件");
}
}
protected void btn_Download_Click(object sender, EventArgs e)
{
//從config中讀取文件上傳路徑
string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
//從列表框控件中讀取選擇的文件名
string strFileName = lb_FileList.SelectedValue;
//組合成物理路徑
string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
//清空輸出流
Response.Clear();
//在HTTP頭中加入文件名信息
Response.AddHeader("Content-Disposition", "attachment;FileName=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));
//定義輸出流MIME類型爲
Response.ContentType = "application/octet-stream";
//從磁盤讀取文件流
System.IO.FileStream fs = System.IO.File.OpenRead(strFilePhysicalPath);
//定義緩衝區大小
byte[] buffer = new byte[102400];
//第一次讀取
int i = fs.Read(buffer, 0, buffer.Length);
//如果讀取的字節大於0,則使用BinaryWrite()不斷向客戶端輸出文件流
while (i > 0)
{
Response.BinaryWrite(buffer);
i = fs.Read(buffer, 0, buffer.Length);
}
//關閉磁盤文件流
fs.Close();
//關閉輸出流
Response.End();
}
protected void btn_Delete_Click(object sender, EventArgs e)
{
//從config中讀取文件上傳路徑
string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
//從列表框控件中讀取選擇的文件名
string strFileName = lb_FileList.SelectedValue;
//組合成物理路徑
string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
//刪除文件
System.IO.File.Delete(strFilePhysicalPath);
//更新文件列表框控件
lb_FileList.Items.Remove(lb_FileList.Items.FindByText(strFileName));
//更新文件夾信息
InitFolderInfo();
//更新文件描述信息
tb_FileNewName.Text = "";
//更新重命名文本框
lab_FileDescription.Text = "";
//調用自定義方法顯示提示
ShowMessageBox("文件成功刪除");
}
protected void btn_Rename_Click(object sender, EventArgs e)
{
//從config中讀取文件上傳路徑
string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
//從列表框控件中讀取選擇的文件名
string strFileName = lb_FileList.SelectedValue;
//從重命名文本框中讀取新文件名
string strFileNewName = tb_FileNewName.Text;
//組合成物理路徑
string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
//組合成物理路徑
string strFileNewPhysicalPath = Server.MapPath(strFileUploadPath + strFileNewName);
//文件重命名
System.IO.File.Move(strFilePhysicalPath, strFileNewPhysicalPath);
//找到文件列表框控件中的匹配項
ListItem li = lb_FileList.Items.FindByText(strFileName);
//修改文字
li.Text = strFileNewName;
//修改值
li.Value = strFileNewName;
//調用自定義方法顯示提示
ShowMessageBox("文件成功重命名");
}
protected void lb_FileList_SelectedIndexChanged(object sender, EventArgs e)
{
//從config中讀取文件上傳路徑
string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
//從列表框控件中讀取選擇的文件名
string strFileName = lb_FileList.SelectedValue;
//組合成物理路徑
string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
//根據物理路徑實例化文件信息類
FileInfo fi = new FileInfo(strFilePhysicalPath);
//獲得文件大小和創建時間並賦值給標籤
lab_FileDescription.Text = string.Format("文件大小:{0} 字節<br><br>上傳時間:{1}<br>", fi.Length, fi.CreationTime);
//把文件名賦值給重命名文本框
tb_FileNewName.Text = strFileName;
}
private void InitFolderInfo()
{
//從config中讀取文件上傳路徑
string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
//判斷上傳文件夾是否存在
if (!Directory.Exists(Server.MapPath(strFileUploadPath)))
Directory.CreateDirectory(Server.MapPath(strFileUploadPath));
//組合成物理路徑
string strFilePath = Server.MapPath(strFileUploadPath);
//從config中讀取文件夾容量限制
double iFolderSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FolderSizeLimit"]);
//聲明表示文件夾已用空間的變量並賦初始值
double iFolderCurrentSize = 0;
//獲取文件夾中所有文件
FileInfo[] arrFiles = new DirectoryInfo(strFilePath).GetFiles();
//累加文件大小獲得已用空間值
foreach (FileInfo fi in arrFiles)
iFolderCurrentSize += Convert.ToInt32(fi.Length / 1024);
//把文件夾容量和已用空間信息賦值給標籤
lab_FolderInfo.Text = string.Format("文件夾容量限制:{0} M 已用空間:{1:f2} M", iFolderSizeLimit / 1024, iFolderCurrentSize / 1024);
}
private void InitUploadLimit()
{
//從config中讀取上傳文件類型限制並根據逗號分割成字符串數組
string[] arrFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString().Split(',');
//從config中讀取上傳文件大小限制
double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]);
//遍歷字符串數組把所有項加入項目編號控件
for (int i = 0; i < arrFileTypeLimit.Length; i++)
bl_FileTypeLimit.Items.Add(arrFileTypeLimit[i].ToString());
//把文件大小限制賦值給標籤
lab_FileSizeLimit.Text = string.Format("{0:f2} M", iFileSizeLimit / 1024);
}
private void InitFileList()
{
//從config中讀取文件上傳路徑
string strFileUploadPath = ConfigurationManager.AppSettings["FileUploadPath"].ToString();
//組合成物理路徑
string strFilePath = Server.MapPath(strFileUploadPath);
//讀取文件夾下所有文件
FileInfo[] arrFiles = new DirectoryInfo(strFilePath).GetFiles();
//把文件名逐一添加到列表框控件控件
foreach (FileInfo fi in arrFiles)
lb_FileList.Items.Add(fi.Name);
}
private bool IsAllowableFileSize()
{
//從config中讀取上傳文件大小限制
double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;
//文件大小是否超出了大小限制?
if (iFileSizeLimit > FileUpload.PostedFile.ContentLength)
return true;
else
return false;
}
private bool IsAllowableFileType()
{
//從config中讀取上傳文件類型限制
string strFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString();
//當前文件擴展名是否能在這個字符串中找到?
if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUpload.FileName).ToLower()) > -1)
return true;
else
return false;
}
private void ShowMessageBox(string strMessaage)
{
ClientScript.RegisterStartupScript(this.GetType(), "", string.Format("<script>alert('{0}')</script>", strMessaage));
}
}
===========================================================================
如果覺得對您有幫助,微信掃一掃支持一下: