• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ASP.NET中常用的附件上传下载

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

在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="width:800px; background-color:#D2D2D2; text-align:left;" align="center" cellpadding="0" cellspacing="1">
<tr style="height:25px; background-color:#EEEEEE;">
<td style="width:500px;">&nbsp;附件名称</td>
<td style="width:140px;">&nbsp;上传人</td>
<td style="width:100px;">&nbsp;上传时间</td>
<td style="width:60px;">&nbsp;操作</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">&nbsp;<%# Eval("AttName") %></a></td>
<td>&nbsp;<%# Eval("UploadBy") %></td>
<td>&nbsp;<%# Eval("UploadDate") %></td>
<td>&nbsp;<asp:LinkButton ID="lbDeleteAtt" runat="server" Text="删除" CommandName="DeleAtt" ></asp:LinkButton></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>

<table style="width: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" />&nbsp;
<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(" ", "&nbsp;") + "');</script>");
else
this.Page.ClientScript.RegisterStartupScript(GetType(), "alert", "<script>alert('" + strMsg.Replace("\r\n", "<br />").Replace(" ", "&nbsp;") + "');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>


 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Winform登录窗体登录仿asp.net验证成功后进入主界面发布时间:2022-07-10
下一篇:
asp.net获取网站根目录发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap