在NET项目中,常常会遇到附件上传下载功能的开发,这里把我的代码分享给大家,希望对大家有帮助,同时也希望大虾们能予以指点。
1.新建用户控件UC_Attachment.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UC_Attachment.ascx.cs" Inherits="DH.WorkFlow.Platform.WorkSpace.WebControls.UC_Attachment" %>
<table style="800px; background-color:#D2D2D2; text-align:left;" align="center" cellpadding="0" cellspacing="1">
<tr style="height:25px; background-color:#EEEEEE;">
<td style="500px;"> 附件名称</td>
<td style="140px;"> 上传人</td>
<td style="100px;"> 上传时间</td>
<td style="60px;"> 操作</td>
</tr>
<asp:Repeater ID="rptAttachment" runat="server" OnItemCommand="rptAttachment_ItemCommand" >
<ItemTemplate>
<tr style="height:25px; background-color:#FFFFFF;">
<td><a href='/Images/DownloadAttachment.aspx?FileReName=<%# Eval("AttReName") %>' target="_blank"> <%# Eval("AttName") %></a></td>
<td> <%# Eval("UploadBy") %></td>
<td> <%# Eval("UploadDate") %></td>
<td> <asp:LinkButton ID="lbDeleteAtt" runat="server" Text="删除" CommandName="DeleAtt" ></asp:LinkButton></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<table style="800px; background-color:#FFFFFF; text-align:left;" align="center" cellpadding="0" cellspacing="0">
<tr>
<td>(提示:单个文件须小于10M !)</td>
<td align="right" height="25px">
<asp:FileUpload ID="FileUpload1" runat="server" Width="300px" BorderStyle="Solid" BorderWidth="1px" />
<asp:Button ID="AddAttachment" runat="server" Text="上 传" CssClass="button2" onclick="AddAttachment_Click" />
</td>
</tr>
</table>
2.用户控件的CS文件UC_Attachment.ascx.cs代码如下
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
namespace DH.WorkFlow.Platform.WorkSpace.WebControls
{
public partial class UC_Attachment : System.Web.UI.UserControl
{
public DataTable AttachmentTable
{
get
{
if (ViewState["AttachmentTable"] != null)
{
return ViewState["AttachmentTable"] as DataTable;
}
else
{
DataTable dt = new DataTable();
dt.Columns.Add("AttName");
dt.Columns.Add("AttReName");
dt.Columns.Add("UploadBy");
dt.Columns.Add("UploadDate");
dt.Columns.Add("AttFullPath");
dt.Columns.Add("AttRemarks");
return dt;
}
}
set { ViewState["AttachmentTable"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
#region 上传附件
protected void AddAttachment_Click(object sender, EventArgs e)
{
int fileLength = FileUpload1.PostedFile.ContentLength;
string fileName = FileUpload1.FileName;
string fileType = fileName.Substring(fileName.LastIndexOf('.') + 1, FileUpload1.FileName.Length - fileName.LastIndexOf('.') - 1);
string[] arrTypes = new string[] { "chm", "doc", "docx", "txt", "text", "png", "mht", "xls", "xlsx", "ppt", "pptx", "jpg", "gif" };
if (fileLength < 0)
{
AlertMessage("上传文件为空或者文件大小为0!", string.Empty);
return;
}
if (fileLength > (10 * 1024 * 1024))
{
AlertMessage("上传文件必须小于10M!", string.Empty);
return;
}
if (!arrTypes.Contains(fileType))
{
AlertMessage("上传文件格式有误!", string.Empty);
return;
}
try
{
string uploadPath = System.Configuration.ConfigurationManager.AppSettings["UploadPath"];
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
string strReFileName = DateTime.Now.ToString("yyMMddHHmmssfff") + FileUpload1.FileName;
string strFileFullPath = uploadPath + strReFileName;
FileUpload1.SaveAs(strFileFullPath);
using (DataTable dt = GetAttachmentTable())
{
DataRow row = dt.NewRow();
row["AttName"] = FileUpload1.FileName;
row["AttReName"] = strReFileName;
row["UploadBy"] = DH.WF.BaseFramework.Organizations.Employee.Current.NameWithDomainName;
row["UploadDate"] = DateTime.Now.ToString("yyyy-MM-dd");
row["AttFullPath"] = strFileFullPath;
row["AttRemarks"] = string.Empty;
dt.Rows.Add(row);
BindAttachment(dt);
}
}
catch (Exception ex)
{
AlertMessage("文件上传过程中出现错误:" + ex.Message, string.Empty);
}
}
private DataTable GetAttachmentTable()
{
return AttachmentTable;
}
private void BindAttachment(DataTable dt)
{
AttachmentTable = dt;
rptAttachment.DataSource = dt;
rptAttachment.DataBind();
}
protected void rptAttachment_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "DeleAtt")
{
using (DataTable dt = GetAttachmentTable())
{
DataRow row = dt.Rows[e.Item.ItemIndex];
string strFileFullPath = row["AttFullPath"].ToString();
if (File.Exists(strFileFullPath))
File.Delete(strFileFullPath);
dt.Rows.RemoveAt(e.Item.ItemIndex);
BindAttachment(dt);
}
}
}
#endregion
private void AlertMessage(string strMsg, string strUrl)
{
if (string.IsNullOrEmpty(strUrl))
this.Page.ClientScript.RegisterStartupScript(GetType(), "alert", "<script>alert('" + strMsg.Replace("\r\n", "<br />").Replace(" ", " ") + "');</script>");
else
this.Page.ClientScript.RegisterStartupScript(GetType(), "alert", "<script>alert('" + strMsg.Replace("\r\n", "<br />").Replace(" ", " ") + "');window.location.href='" + strUrl + "';</script>");
}
}
}
3.下载页面DownloadAttachment.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DownloadAttachment.aspx" %>
<!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>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string agrFileReName = Request.QueryString["FileReName"] != null ? Request.QueryString["FileReName"] : "";
string uploadPath = System.Configuration.ConfigurationManager.AppSettings["UploadPath"];
string fileFullPath = uploadPath + agrFileReName;
if (!string.IsNullOrEmpty(agrFileReName))
{
System.IO.FileInfo fi = new System.IO.FileInfo(fileFullPath);
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(agrFileReName));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", fi.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.WriteFile(fi.FullName);
// 停止页面的执行
//Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>