
采菇凉的小蘑菇 - 云代码空间
—— 为了老婆,好好工作。
using System;
namespace Colliery.Model
{
/// <summary>
/// 附件
/// </summary>
[Serializable]
public partial class Comm_AnnexInfo
{
public Comm_AnnexInfo()
{ }
#region Model
public static string Comm_Annex_Table = "Comm_Annex";
public static string ID_Field = "ID";
public static string DataID_Field = "DataID";
public static string FileName_Field = "FileName";
public static string FilePath_Field = "FilePath";
public static string CreatedBy_Field = "CreatedBy";
public static string CreatedDate_Field = "CreatedDate";
public static string ModifiedBy_Field = "ModifiedBy";
public static string ModifiedDate_Field = "ModifiedDate";
private string _id;
private string _dataid;
private string _filename;
private string _filepath;
private string _createdby = "SystemAdmin";
private DateTime? _createddate = DateTime.Now;
private string _modifiedby = "SystemAdmin";
private DateTime? _modifieddate = DateTime.Now;
/// <summary>
///
/// </summary>
public string ID
{
set { _id = value; }
get { return _id; }
}
/// <summary>
/// 主表数据ID
/// </summary>
public string DataID
{
set { _dataid = value; }
get { return _dataid; }
}
/// <summary>
/// 附件文件名
/// </summary>
public string FileName
{
set { _filename = value; }
get { return _filename; }
}
/// <summary>
/// 附件路径
/// </summary>
public string FilePath
{
set { _filepath = value; }
get { return _filepath; }
}
/// <summary>
/// 创建人
/// </summary>
public string CreatedBy
{
set { _createdby = value; }
get { return _createdby; }
}
/// <summary>
/// 创建时间
/// </summary>
public DateTime? CreatedDate
{
set { _createddate = value; }
get { return _createddate; }
}
/// <summary>
/// 修改人
/// </summary>
public string ModifiedBy
{
set { _modifiedby = value; }
get { return _modifiedby; }
}
/// <summary>
/// 修改时间
/// </summary>
public DateTime? ModifiedDate
{
set { _modifieddate = value; }
get { return _modifieddate; }
}
#endregion Model
}
}
dal层:using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Data.SqlClient;
using XSAT.Lib2014.System.Data;//Please add references
using Colliery.Model;
namespace Colliery.DAL
{
/// <summary>
/// 数据访问类:Comm_AnnexDAL
/// </summary>
public partial class Comm_AnnexDAL
{
public Comm_AnnexDAL()
{ }
#region BasicMethod
/// <summary>
/// 增加一条数据
/// <param name="model">实体</param>
/// </summary>
public bool Add(Comm_AnnexInfo model)
{
StringBuilder strSql = new StringBuilder();
int n = 0;
strSql.Append("insert into Comm_Annex(");
strSql.Append("ID,DataID,FileName,FilePath,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate)");
strSql.Append(" values (");
strSql.Append("@ID,@DataID,@FileName,@FilePath,@CreatedBy,@CreatedDate,@ModifiedBy,@ModifiedDate)");
SqlParameter[] parameters = {
new SqlParameter("@ID", SqlDbType.VarChar,64),
new SqlParameter("@DataID", SqlDbType.VarChar,64),
new SqlParameter("@FileName", SqlDbType.NVarChar),
new SqlParameter("@FilePath", SqlDbType.NVarChar),
new SqlParameter("@CreatedBy", SqlDbType.VarChar,64),
new SqlParameter("@CreatedDate", SqlDbType.DateTime),
new SqlParameter("@ModifiedBy", SqlDbType.VarChar,64),
new SqlParameter("@ModifiedDate", SqlDbType.DateTime)};
parameters[n++].Value = model.ID;
parameters[n++].Value = model.DataID;
parameters[n++].Value = model.FileName;
parameters[n++].Value = model.FilePath;
parameters[n++].Value = model.CreatedBy;
parameters[n++].Value = model.CreatedDate;
parameters[n++].Value = model.ModifiedBy;
parameters[n++].Value = model.ModifiedDate;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 更新一条数据
/// <param name="model">实体</param>
/// </summary>
public bool Update(Comm_AnnexInfo model)
{
StringBuilder strSql = new StringBuilder();
int n = 0;
strSql.Append("update Comm_Annex set ");
strSql.Append("DataID=@DataID,");
strSql.Append("FileName=@FileName,");
strSql.Append("FilePath=@FilePath,");
strSql.Append("CreatedBy=@CreatedBy,");
strSql.Append("CreatedDate=@CreatedDate,");
strSql.Append("ModifiedBy=@ModifiedBy,");
strSql.Append("ModifiedDate=@ModifiedDate");
strSql.Append(" where ID=@ID ");
SqlParameter[] parameters = {
new SqlParameter("@DataID", SqlDbType.VarChar,64),
new SqlParameter("@FileName", SqlDbType.NVarChar),
new SqlParameter("@FilePath", SqlDbType.NVarChar),
new SqlParameter("@CreatedBy", SqlDbType.VarChar,64),
new SqlParameter("@CreatedDate", SqlDbType.DateTime),
new SqlParameter("@ModifiedBy", SqlDbType.VarChar,64),
new SqlParameter("@ModifiedDate", SqlDbType.DateTime),
new SqlParameter("@ID", SqlDbType.VarChar,64)};
parameters[n++].Value = model.DataID;
parameters[n++].Value = model.FileName;
parameters[n++].Value = model.FilePath;
parameters[n++].Value = model.CreatedBy;
parameters[n++].Value = model.CreatedDate;
parameters[n++].Value = model.ModifiedBy;
parameters[n++].Value = model.ModifiedDate;
parameters[n++].Value = model.ID;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// <param name="ID">ID</param>
/// </summary>
public bool Delete(string ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from Comm_Annex ");
strSql.Append(" where ID=@ID ");
SqlParameter[] parameters = {
new SqlParameter("@ID", SqlDbType.VarChar,64) };
parameters[0].Value = ID;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// <param name="ID">ID</param>
/// </summary>
public Comm_AnnexInfo GetModel(string ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 ID,DataID,FileName,FilePath,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate from Comm_Annex ");
strSql.Append(" where ID=@ID ");
SqlParameter[] parameters = {
new SqlParameter("@ID", SqlDbType.VarChar,64) };
parameters[0].Value = ID;
Comm_AnnexInfo model = new Comm_AnnexInfo();
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public Comm_AnnexInfo DataRowToModel(DataRow row)
{
Comm_AnnexInfo model = new Comm_AnnexInfo();
if (row != null)
{
if (row["ID"] != null)
{
model.ID = row["ID"].ToString();
}
if (row["DataID"] != null)
{
model.DataID = row["DataID"].ToString();
}
if (row["FileName"] != null)
{
model.FileName = row["FileName"].ToString();
}
if (row["FilePath"] != null)
{
model.FilePath = row["FilePath"].ToString();
}
if (row["CreatedBy"] != null)
{
model.CreatedBy = row["CreatedBy"].ToString();
}
if (row["CreatedDate"] != null && row["CreatedDate"].ToString() != "")
{
model.CreatedDate = DateTime.Parse(row["CreatedDate"].ToString());
}
if (row["ModifiedBy"] != null)
{
model.ModifiedBy = row["ModifiedBy"].ToString();
}
if (row["ModifiedDate"] != null && row["ModifiedDate"].ToString() != "")
{
model.ModifiedDate = DateTime.Parse(row["ModifiedDate"].ToString());
}
}
return model;
}
/// <summary>
/// 获得前几行数据
/// <param name="QueryBuilder"></param>
/// </summary>
public List<Comm_AnnexInfo> GetList(QueryBuilder queryBuilder)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select ");
if (queryBuilder.Top > 0)
{
strSql.Append(" top " + queryBuilder.Top);
}
strSql.Append(" ID,DataID,FileName,FilePath,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate ");
strSql.Append(" FROM Comm_Annex ");
strSql.Append(queryBuilder.Where);
strSql.Append(queryBuilder.Order);
DataSet ds = DbHelperSQL.Query(strSql.ToString());
List<Comm_AnnexInfo> list = new List<Comm_AnnexInfo>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
list.Add(DataRowToModel(dr));
}
return list;
}
/// <summary>
/// 分页获取数据列表
/// <param name="queryBuilder"></param>
/// <param name="iRecordCount"></param>
/// </summary>
public DataTable GetListByPage(QueryBuilder queryBuilder, ref int iRecordCount)
{
StringBuilder sbSql = new StringBuilder();
sbSql.Append("SELECT * FROM Comm_Annex" + queryBuilder.Where);
IDataParameter[] para = new IDataParameter[]
{
new SqlParameter("@PageIndex",SqlDbType.Int),
new SqlParameter("@PageSize",SqlDbType.Int),
new SqlParameter("@strSql",SqlDbType.VarChar),
new SqlParameter("@Field",SqlDbType.VarChar),
new SqlParameter("@OrderField",SqlDbType.VarChar)
};
para[0].Value = queryBuilder.PageIndex;
para[1].Value = queryBuilder.PageSize;
para[2].Value = sbSql.ToString();
para[3].Value = queryBuilder.OrderField;
para[4].Value = queryBuilder.OrderType;
DataSet ds = DbHelperSQL.RunProcedure("ExecutePaging", para, "Comm_Annex");
try
{
iRecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
return ds.Tables[0];
}
catch
{
return null;
}
}
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
using System;
using System.Data;
using System.Collections.Generic;
using XSAT.Lib2014.System.Data;//Please add references
using Colliery.DAL;
using Colliery.Model;
namespace Colliery.BLL
{
/// <summary>
/// 附件
/// </summary>
public partial class Comm_AnnexBLL
{
private Comm_AnnexDAL dal = new Comm_AnnexDAL();
#region BasicMethod
/// <summary>
/// 增加一条数据
/// <param name="model">实体</param>
/// </summary>
public bool Add(Comm_AnnexInfo model)
{
return dal.Add(model);
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(Comm_AnnexInfo model)
{
return dal.Update(model);
}
/// <summary>
/// 删除一条数据
/// <param name="ID">ID</param>
/// </summary>
public bool Delete(string ID)
{
return dal.Delete(ID);
}
/// <summary>
/// 得到一个对象实体
/// <param name="ID">ID</param>
/// </summary>
public Comm_AnnexInfo GetModel(string ID)
{
return dal.GetModel(ID);
}
/// <summary>
/// 获得前几行数据
/// <param name="queryBuilder"></param>
/// </summary>
public List<Comm_AnnexInfo> GetList(QueryBuilder queryBuilder)
{
return dal.GetList(queryBuilder);
}
/// <summary>
/// 分页获取数据列表
/// <param name="queryBuilder"></param>
/// <param name="iRecordCount"></param>
/// </summary>
public DataTable GetListByPage(QueryBuilder queryBuilder, ref int iRecordCount)
{
return dal.GetListByPage(queryBuilder, ref iRecordCount);
}
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
三层结构建好以后,在页面中设置添加一个上传按钮和一个div(显示上传文件),并设置它们的属性,前台属性如下:<asp:Button ID="btnUpLoad" runat="server" Anx="y" Text="上传" AnxID="" />
<div id="divZGOpinion" class="Anx" runat="server"></div>
在后台代码中只要给上传按钮的Attributes属性添加一个ID就好了,用于附件在表中的唯一标示,同时是附件表与主表的外键连接。代码如下:// Guid.NewGuid()方法用于生成随机字符串避免重复 this.btnUpLoad.Attributes["AnxID"] = Guid.NewGuid().ToString(); //页面初始化设置按钮属性
model.FuJian = this.btnZGOpinion.Attributes["AnxID"]; //表单添加的时候将附件添加到数据库 bll.Add(model);
$(function () {
$("[Anx='y']").click(function () {
var arr = window.showModalDialog("/Window/UpLoadFile.aspx?ID=" + $(this).attr("AnxID"), '', 'dialogWidth=800px;dialogHeight=600px;help:no;status:no');
if (arr != undefined) {
var $div = $(this).next();
var html = "";
for (var i = 0; i < arr.length; i++) {
if (arr[i] != null) {
html += "<p><a href='" + arr[i] + "' target='_blank'>" + arr[i++] + "</a></p>";
}
}
$div.html(html);
}
return false;
});
});
上述代码可以看出是利用弹出界面上传文件并获得上传文件列表的返回值绑定给上传按钮的下一个div元素,用于显示上传文件并支持点击打开或下载,那么弹出窗口UpLoadFile.aspx的代码就是通常情况下通用的一套简单的文件上传代码了,前台代码如下所示:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpLoadFile.aspx.cs" Inherits="Colliery.Manage.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 id="Head1" runat="server">
<base target="_self">
<title></title>
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#btnDetailClose").click(function () {
//getData();
window.close();
return false;
});
});
//window.onbeforeunload = function () {
// getData();
//}
function getData() {
var arr = new Array();
var i = 0;
$(".gridView tr").each(function () {
arr[i++] = $(this).find("td").eq(0).html();
arr[i++] = $(this).find("td").eq(1).html();
});
window.returnValue = arr;
//window.close();
//return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField ID="hidDataID" runat="server" />
<div class="detailTitle">
<div>
</div>
<span>明细</span>
</div>
<div class="detailArea">
<table class="detailTable" cellspacing="0" cellpadding="0">
<tr>
<td class="detailTableTd1">附件:</td>
<td class="detailTableTd2">
<asp:FileUpload ID="fileUpload" runat="server" />
</td>
</tr>
</table>
<div class="btnArea">
<asp:ImageButton ID="btnDetailClose" runat="server" ImageUrl="/Image/Return.png" />
<asp:ImageButton ID="btnAdd" ImageUrl="/Image/Save.png" runat="server" vbtn="y" OnClick="btnAdd_Click" />
</div>
</div>
<div class="detailTitle">
<div>
</div>
<span>搜索结果</span>
</div>
<div class="detailArea">
<!--GridView-->
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" Width="100%" OnRowCommand="GridViewPositionList_RowCommand" CssClass="gridView">
<Columns>
<asp:BoundField DataField="FileName" HeaderText="附件文件名" />
<asp:BoundField DataField="FilePath" HeaderText="路径" />
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:LinkButton ID="Dele" runat="server" CommandName="_delete" CommandArgument='<%# Eval("ID")%>' OnClientClick="return confirm('是否删除?');">删除</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="80px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<!--End GridView-->
</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 Colliery.BLL;
using Colliery.Model;
using System.IO;
namespace Colliery.Manage
{
public partial class UpLoadFile : BasePager
{
//int iRecordCount = 0;
Comm_AnnexBLL bll = new Comm_AnnexBLL();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request["ID"]))
{
hidDataID.Value = Request["ID"];
}
}
bind();
}
protected void GridViewPositionList_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToString())
{
case "_delete":
Comm_AnnexInfo model = new Comm_AnnexBLL().GetModel(e.CommandArgument.ToString());
if (File.Exists(Server.MapPath("..") + model.FilePath))
{
File.Delete(Server.MapPath("..") + model.FilePath);
}
MessageBox.Show(this, bll.Delete(e.CommandArgument.ToString()) ? "删除成功" : "删除失败");
break;
}
bind();
Page.ClientScript.RegisterStartupScript(this.GetType(), "getdate", "<script>getData();</script>");
}
void bind()
{
QueryBuilder queryBuilder = new QueryBuilder();
queryBuilder.AddFilter(Comm_AnnexInfo.DataID_Field, "=", hidDataID.Value);
gridView.DataSource = bll.GetList(queryBuilder);
gridView.DataBind();
}
protected void btnAdd_Click(object sender, ImageClickEventArgs e)
{
if (fileUpload.HasFile)
{
Comm_AnnexInfo model = new Comm_AnnexInfo();
model.ID = Guid.NewGuid().ToString();
model.DataID = hidDataID.Value;
model.FileName = fileUpload.FileName;
model.FilePath = "/UpLoadFile/Annex/" + DateTime.Now.ToString("yyyyMMdd") + "/" + DateTime.Now.ToString("HH");
string filePath = Server.MapPath("..") + model.FilePath;
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string fileType = "";
bool b = false;
fileType = Path.GetExtension(fileUpload.PostedFile.FileName).ToLower();
string[] type = { ".doc", ".docx",".wps", ".xls", ".xlsx", ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
foreach (string extension in type)
{
if (extension == fileType)
{
b = true;
break;
}
}
if (!b)
{
MessageBox.Show(this.Page,"文件格式不正确,请重新选择!!!");
return;
}
model.FilePath += "/" + DateTime.Now.Ticks + fileType;
fileUpload.SaveAs(Server.MapPath("..") + model.FilePath);
#region 给图片添加水印
if (fileType==".jpg" || fileType==".jepg" || fileType==".png" || fileType=="gif" || fileType==".bmp")
{
string path = "";
WaterImage iamages = new WaterImage(Server.MapPath("..") + model.FilePath);
if (fileUpload.PostedFile.ContentLength > 1048576)
{
//path = iamages.MakeThumbnail(model.FilePath, 1024, 768, "Cut");
MessageBox.Show(this, "上传图片不能超过1M,请重新选择!!!");
return;
}
else
path = model.FilePath;
string urltp = iamages.Save(path);
model.FilePath = urltp;
}
#endregion
new Comm_AnnexBLL().Add(model);
MessageBox.Show(this, "上传成功!");
bind();
Page.ClientScript.RegisterStartupScript(this.GetType(), "getdate", "<script>getData();</script>");
}
}
}
}
private void ShowInfo()
{
this.btnZGOpinion.Attributes["AnxID"] = model.FuJian.ToString();
_FWAnnexBind(this.btnZGOpinion, this.divZGOpinion);
}
public void _FWAnnexBind(Button btn, HtmlGenericControl div)
{
QueryBuilder queryBuilder = new QueryBuilder();
queryBuilder.AddFilter(Comm_AnnexInfo.DataID_Field, "=", btn.Attributes["AnxID"]);
List<Comm_AnnexInfo> list = new Comm_AnnexBLL().GetList(queryBuilder);
string html = "";
foreach (Comm_AnnexInfo model in list)
{
html += "<p><a href='" + model.FilePath + "' target='_blank'>" + model.FileName + "</a></p>";
}
div.InnerHtml = html;
}
这样一个完整的附件上传及显示就完成了。