通用附件上传方法
在我们写程序的时候在很多地方都会用到附件上传。一个简单通用的附件上传方式可以有效的节省开发工作。
在这里我介绍一种比较通用的附件上传方式,和Exchange中的附件上传方式相似。
在我们写程序的时候在很多地方都会用到附件上传。一个简单通用的附件上传方式可以有效的节省开发工作。
在这里我介绍一种比较通用的附件上传方式,和Exchange中的附件上传方式相似。
下面是运行的效果图:
先来看一下表结构:
Code
CREATE TABLE [dbo].[Com_TAttachments](
[FFileId] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL,--附件序号
[FTableName] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,--主表名
[FPk] [int] NULL, --主表主键值
[FFileName] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL, --附件名
[FExtension] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL, --附件扩展名
[FContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,--附件文件类型
[FContent] [image] NULL, --附件内容
[FSize] [bigint] NULL, --附件大小
[FRemark] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL, --备注
[FCreateUserId] [int] NULL, --创建人
[FCreateDate] [datetime] NULL, --创建时间
)
CREATE TABLE [dbo].[Com_TAttachments](
[FFileId] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL,--附件序号
[FTableName] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL,--主表名
[FPk] [int] NULL, --主表主键值
[FFileName] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL, --附件名
[FExtension] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL, --附件扩展名
[FContentType] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,--附件文件类型
[FContent] [image] NULL, --附件内容
[FSize] [bigint] NULL, --附件大小
[FRemark] [varchar](255) COLLATE Chinese_PRC_CI_AS NULL, --备注
[FCreateUserId] [int] NULL, --创建人
[FCreateDate] [datetime] NULL, --创建时间
)
在这里我是将上传的文件保存到数据库中,当然如果开发的系统应用过程中上传的文件很多,很大,也可以保存上传文件路径的方式。
下面看一下附件上传页面:
Code
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeBehind="UpLoadFile.aspx.cs" Inherits="YKSoft.OA.Pages.Attachment.UpLoadFile" %>
<!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>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Cache-Control" content="no-cache">
<base target="_self" />
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
//返回的上传附件Id,临时保存的父窗口控件hidden的Id。
var IdControl="<%=IdControl %>";
//返回的上传附件名称,临时保存的父窗口控件DIV的Id
var NameControl="<%=NameControl %>";
//附加、删除
function addfile()
{
var ids=document.getElementById("<%=hidValue.ClientID %>").value;
var names=document.getElementById("<%=hidName.ClientID %>").value;
if(dialogArguments.doc.getElementById(NameControl)!=null)
dialogArguments.doc.getElementById(NameControl).innerHTML =names;
if(dialogArguments.doc.getElementById(IdControl)!=null)
dialogArguments.doc.getElementById(IdControl).value =ids;
}
//确定
function ok()
{
addfile();
this.close();
}
</script>
<div>
<table width="100%">
<tr>
<td>
<asp:FileUpload ID="file" runat="server" Width="100%" /></td>
</tr>
<tr>
<td>
<table style="width:100%">
<tr>
<td style="width: 80%" valign="top">
</td>
<td align="center" style="width: 20%" valign="middle">
<asp:Button ID="btnUpLoad" runat="server" Text="附加" OnClick="btnUpLoad_Click" /></td>
</tr>
<tr>
<td style="width:80%" valign="top">
<asp:Panel ID="PlFile" runat="server" Height="150px" ScrollBars="Auto" Width="100%" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px">
<asp:CheckBoxList ID="cboFileList" runat="server">
</asp:CheckBoxList></asp:Panel>
</td>
<td style="width:20%" align="center" valign="middle">
<asp:Button ID="btnDel" runat="server" Text="删除" Enabled="False" OnClick="btnDel_Click" /><br />
<br />
<br />
<br />
<input id="btnOK" type="button" value="确定" onclick="ok();" /></td>
</tr>
</table>
<asp:HiddenField ID="hidValue" runat="server" />
<asp:HiddenField ID="hidName" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeBehind="UpLoadFile.aspx.cs" Inherits="YKSoft.OA.Pages.Attachment.UpLoadFile" %>
<!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>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Cache-Control" content="no-cache">
<base target="_self" />
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
//返回的上传附件Id,临时保存的父窗口控件hidden的Id。
var IdControl="<%=IdControl %>";
//返回的上传附件名称,临时保存的父窗口控件DIV的Id
var NameControl="<%=NameControl %>";
//附加、删除
function addfile()
{
var ids=document.getElementById("<%=hidValue.ClientID %>").value;
var names=document.getElementById("<%=hidName.ClientID %>").value;
if(dialogArguments.doc.getElementById(NameControl)!=null)
dialogArguments.doc.getElementById(NameControl).innerHTML =names;
if(dialogArguments.doc.getElementById(IdControl)!=null)
dialogArguments.doc.getElementById(IdControl).value =ids;
}
//确定
function ok()
{
addfile();
this.close();
}
</script>
<div>
<table width="100%">
<tr>
<td>
<asp:FileUpload ID="file" runat="server" Width="100%" /></td>
</tr>
<tr>
<td>
<table style="width:100%">
<tr>
<td style="width: 80%" valign="top">
</td>
<td align="center" style="width: 20%" valign="middle">
<asp:Button ID="btnUpLoad" runat="server" Text="附加" OnClick="btnUpLoad_Click" /></td>
</tr>
<tr>
<td style="width:80%" valign="top">
<asp:Panel ID="PlFile" runat="server" Height="150px" ScrollBars="Auto" Width="100%" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px">
<asp:CheckBoxList ID="cboFileList" runat="server">
</asp:CheckBoxList></asp:Panel>
</td>
<td style="width:20%" align="center" valign="middle">
<asp:Button ID="btnDel" runat="server" Text="删除" Enabled="False" OnClick="btnDel_Click" /><br />
<br />
<br />
<br />
<input id="btnOK" type="button" value="确定" onclick="ok();" /></td>
</tr>
</table>
<asp:HiddenField ID="hidValue" runat="server" />
<asp:HiddenField ID="hidName" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace YKSoft.OA.Pages.Attachment
{
public partial class UpLoadFile : YKSoft.Web.UI.Page.PageBase
{
YKSoft.OA.BLL.Common.ComTAttachments BLL_ComTAttachments = new YKSoft.OA.BLL.Common.ComTAttachments();
//父窗口保存附件Id字符串的控件Id
protected string IdControl = "";
//父窗口保存附件名称字符串的控件Id
protected string NameControl = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request["IdControl"] != null)
IdControl = Request["IdControl"].ToString();
if (Request["NameControl"] != null)
NameControl = Request["NameControl"].ToString();
if (!Page.IsPostBack)
{
//已经上传的附件Id字符串,如:1,3。中间以,分隔。
//此过程是在对已经上传的附件进行修改时运行。
if (Request["Ids"] != null)
{
string[] Ids = Request["Ids"].ToString().Split(',');
//获取已经上传的附件数据集
IList<YKSoft.OA.Model.Common.ComTAttachments> items = BLL_ComTAttachments.GetList(Ids);
//将已经上传的附件添加到附件列表中显示。
for (int i = 0; i < items.Count; i++)
{
cboFileList.Items.Add(new ListItem(items[i].FfileName, items[i].FfileId));
}
SetValueName();
}
}
}
/**//// <summary>
/// 上传附件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpLoad_Click(object sender, EventArgs e)
{
//是否选择了文件
if (file.HasFile)
{
YKSoft.OA.Model.Common.ComTAttachments info = new YKSoft.OA.Model.Common.ComTAttachments();
info.FfileId = Guid.NewGuid().ToString();
info.FcreateDate = DateTime.Now;
info.Fcontent = file.FileBytes;
info.FcontentType = file.PostedFile.ContentType;
info.FfileName = file.FileName.Substring(0, file.FileName.LastIndexOf("."));
info.Fsize = file.PostedFile.ContentLength;
info.Fextension = file.PostedFile.FileName.Substring(file.PostedFile.FileName.LastIndexOf(".") + 1);
info.FcreateUserId = LoginUser.Fuserid;
//保存上传文件到数据库
BLL_ComTAttachments.Save(info);
//添加附件到显示列表中
cboFileList.Items.Add(new ListItem(info.FfileName, info.FfileId.ToString()));
SetValueName();
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>addfile()</script>");
}
else JsAlert("请选择上传文件!");
}
/**//// <summary>
/// 删除附件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnDel_Click(object sender, EventArgs e)
{
for (int i = 0; i < cboFileList.Items.Count; i++)
{
//删除选中的附件
if (cboFileList.Items[i].Selected)
{
string id = cboFileList.Items[i].Value;
//从数据库中删除
BLL_ComTAttachments.Delete(id);
//从显示的列表中删除
cboFileList.Items.RemoveAt(i);
i--;
}
}
SetValueName();
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>addfile()</script>");
}
/**//// <summary>
/// 将选中的上传附件的Id和名称保存到隐藏的控件中。
/// </summary>
protected void SetValueName()
{
hidValue.Value = "";
hidName.Value = "";
for (int i = 0; i < cboFileList.Items.Count; i++)
{
if (String.IsNullOrEmpty(hidValue.Value.Trim()))
{
hidValue.Value = cboFileList.Items[i].Value;
hidName.Value = "<a target=\"_blank\" href=\"../Attachment/download.aspx?ID="+cboFileList.Items[i].Value+"\">"+cboFileList.Items[i].Text+"</a>";
}
else
{
hidValue.Value = hidValue.Value + "," + cboFileList.Items[i].Value;
hidName.Value = hidName.Value + ";" + "<a target=\"_blank\" href=\"../Attachment/download.aspx?ID=" + cboFileList.Items[i].Value + "\">" + cboFileList.Items[i].Text + "</a>";
}
}
if (cboFileList.Items.Count > 0)
btnDel.Enabled = true;
}
}
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace YKSoft.OA.Pages.Attachment
{
public partial class UpLoadFile : YKSoft.Web.UI.Page.PageBase
{
YKSoft.OA.BLL.Common.ComTAttachments BLL_ComTAttachments = new YKSoft.OA.BLL.Common.ComTAttachments();
//父窗口保存附件Id字符串的控件Id
protected string IdControl = "";
//父窗口保存附件名称字符串的控件Id
protected string NameControl = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request["IdControl"] != null)
IdControl = Request["IdControl"].ToString();
if (Request["NameControl"] != null)
NameControl = Request["NameControl"].ToString();
if (!Page.IsPostBack)
{
//已经上传的附件Id字符串,如:1,3。中间以,分隔。
//此过程是在对已经上传的附件进行修改时运行。
if (Request["Ids"] != null)
{
string[] Ids = Request["Ids"].ToString().Split(',');
//获取已经上传的附件数据集
IList<YKSoft.OA.Model.Common.ComTAttachments> items = BLL_ComTAttachments.GetList(Ids);
//将已经上传的附件添加到附件列表中显示。
for (int i = 0; i < items.Count; i++)
{
cboFileList.Items.Add(new ListItem(items[i].FfileName, items[i].FfileId));
}
SetValueName();
}
}
}
/**//// <summary>
/// 上传附件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpLoad_Click(object sender, EventArgs e)
{
//是否选择了文件
if (file.HasFile)
{
YKSoft.OA.Model.Common.ComTAttachments info = new YKSoft.OA.Model.Common.ComTAttachments();
info.FfileId = Guid.NewGuid().ToString();
info.FcreateDate = DateTime.Now;
info.Fcontent = file.FileBytes;
info.FcontentType = file.PostedFile.ContentType;
info.FfileName = file.FileName.Substring(0, file.FileName.LastIndexOf("."));
info.Fsize = file.PostedFile.ContentLength;
info.Fextension = file.PostedFile.FileName.Substring(file.PostedFile.FileName.LastIndexOf(".") + 1);
info.FcreateUserId = LoginUser.Fuserid;
//保存上传文件到数据库
BLL_ComTAttachments.Save(info);
//添加附件到显示列表中
cboFileList.Items.Add(new ListItem(info.FfileName, info.FfileId.ToString()));
SetValueName();
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>addfile()</script>");
}
else JsAlert("请选择上传文件!");
}
/**//// <summary>
/// 删除附件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnDel_Click(object sender, EventArgs e)
{
for (int i = 0; i < cboFileList.Items.Count; i++)
{
//删除选中的附件
if (cboFileList.Items[i].Selected)
{
string id = cboFileList.Items[i].Value;
//从数据库中删除
BLL_ComTAttachments.Delete(id);
//从显示的列表中删除
cboFileList.Items.RemoveAt(i);
i--;
}
}
SetValueName();
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>addfile()</script>");
}
/**//// <summary>
/// 将选中的上传附件的Id和名称保存到隐藏的控件中。
/// </summary>
protected void SetValueName()
{
hidValue.Value = "";
hidName.Value = "";
for (int i = 0; i < cboFileList.Items.Count; i++)
{
if (String.IsNullOrEmpty(hidValue.Value.Trim()))
{
hidValue.Value = cboFileList.Items[i].Value;
hidName.Value = "<a target=\"_blank\" href=\"../Attachment/download.aspx?ID="+cboFileList.Items[i].Value+"\">"+cboFileList.Items[i].Text+"</a>";
}
else
{
hidValue.Value = hidValue.Value + "," + cboFileList.Items[i].Value;
hidName.Value = hidName.Value + ";" + "<a target=\"_blank\" href=\"../Attachment/download.aspx?ID=" + cboFileList.Items[i].Value + "\">" + cboFileList.Items[i].Text + "</a>";
}
}
if (cboFileList.Items.Count > 0)
btnDel.Enabled = true;
}
}
}
下面写一段Javascript脚本调用代码:
Code
//附件上传
//IdControl:存放附件Id的控件Id,如:<asp:HiddenField ID="HiddenField1" runat="server" />
//NameControl:存放附件的链接地址:如:<div id="divFile" style="width:50px;height:50px"></div>
function FileUpLoad(IdControl,NameControl)
{
var sWidth=400;
var sHeight=300;
var ret;
var url="../Attachment/UpLoadFile.aspx?IdControl="+IdControl+"&NameControl="+NameControl;
var Idvalue=document.getElementById(IdControl).value;
var NameValue=document.getElementById(NameControl).value;
//如果已经上传的附件Id不为空,将附件的Id字符传给上传附件页面。
if(Idvalue!=null&&Idvalue!="")
url+="&Ids="+Idvalue;
ret=window.showModalDialog(encodeURI(url),{doc:document,win:parent},"dialogWidth:"+sWidth+"px;dialogHeight:"+sHeight+"px;resizable:0");
}
//附件上传
//IdControl:存放附件Id的控件Id,如:<asp:HiddenField ID="HiddenField1" runat="server" />
//NameControl:存放附件的链接地址:如:<div id="divFile" style="width:50px;height:50px"></div>
function FileUpLoad(IdControl,NameControl)
{
var sWidth=400;
var sHeight=300;
var ret;
var url="../Attachment/UpLoadFile.aspx?IdControl="+IdControl+"&NameControl="+NameControl;
var Idvalue=document.getElementById(IdControl).value;
var NameValue=document.getElementById(NameControl).value;
//如果已经上传的附件Id不为空,将附件的Id字符传给上传附件页面。
if(Idvalue!=null&&Idvalue!="")
url+="&Ids="+Idvalue;
ret=window.showModalDialog(encodeURI(url),{doc:document,win:parent},"dialogWidth:"+sWidth+"px;dialogHeight:"+sHeight+"px;resizable:0");
}
附件下载页面:
Code
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ID"] != null)
{
string id = Request["ID"].ToString();
YKSoft.OA.Model.Common.ComTAttachments info = (new YKSoft.OA.BLL.Common.ComTAttachments()).GetItem(id);
if (info != null)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(info.FfileName+"."+info.Fextension));
Response.AddHeader("Content-Length", info.Fsize.ToString());
Response.AddHeader("Content-Type", info.FcontentType);
Response.BinaryWrite(info.Fcontent);
Response.End();
}
}
else
throw new Exception("该附件不存在。");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ID"] != null)
{
string id = Request["ID"].ToString();
YKSoft.OA.Model.Common.ComTAttachments info = (new YKSoft.OA.BLL.Common.ComTAttachments()).GetItem(id);
if (info != null)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(info.FfileName+"."+info.Fextension));
Response.AddHeader("Content-Length", info.Fsize.ToString());
Response.AddHeader("Content-Type", info.FcontentType);
Response.BinaryWrite(info.Fcontent);
Response.End();
}
}
else
throw new Exception("该附件不存在。");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
这样我们就可以在需要附件上传的页面调用该功能了,测试页如下:
Code
<%@ Page Language="C#"%>
<!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 src="../Js/Attachment.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" onclick="FileUpLoad('Text1','divFile');">附件上传</a>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<div id="divFile" style="width:50px;height:50px"></div>
</div>
</form>
</body>
</html>
<%@ Page Language="C#"%>
<!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 src="../Js/Attachment.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" onclick="FileUpLoad('Text1','divFile');">附件上传</a>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<div id="divFile" style="width:50px;height:50px"></div>
</div>
</form>
</body>
</html>