通用附件上传方法

在我们写程序的时候在很多地方都会用到附件上传。一个简单通用的附件上传方式可以有效的节省开发工作。

在这里我介绍一种比较通用的附件上传方式,和Exchange中的附件上传方式相似。

下面是运行的效果图:

先来看一下表结构:

 

ContractedBlock.gif ExpandedBlockStart.gif 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,                                --创建时间
)

在这里我是将上传的文件保存到数据库中,当然如果开发的系统应用过程中上传的文件很多,很大,也可以保存上传文件路径的方式。

下面看一下附件上传页面:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
ExpandedBlockStart.gifContractedBlock.gif<%@ 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">
ExpandedBlockStart.gifContractedBlock.gif    
<script type="text/javascript">
     
//返回的上传附件Id,临时保存的父窗口控件hidden的Id。
     var IdControl="<%=IdControl %>";
     
//返回的上传附件名称,临时保存的父窗口控件DIV的Id
     var NameControl="<%=NameControl %>";
  
//附加、删除  
  function addfile()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
{
     
      
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()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
{
     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>

 

 

ContractedBlock.gif ExpandedBlockStart.gif 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
ExpandedBlockStart.gifContractedBlock.gif
{
    
public partial class UpLoadFile : YKSoft.Web.UI.Page.PageBase
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{

            
if (Request["IdControl"!= null)
                IdControl 
= Request["IdControl"].ToString();

            
if (Request["NameControl"!= null)
                NameControl 
= Request["NameControl"].ToString();

            
if (!Page.IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//已经上传的附件Id字符串,如:1,3。中间以,分隔。
                
//此过程是在对已经上传的附件进行修改时运行。
                if (Request["Ids"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
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++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
{
                        cboFileList.Items.Add(
new ListItem(items[i].FfileName, items[i].FfileId));
                    }


                    SetValueName();
                }

            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 上传附件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>

        protected void btnUpLoad_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//是否选择了文件
            if (file.HasFile)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                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("请选择上传文件!");
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 删除附件
        
/// </summary>
        
/// <param name="sender"></param>
        
/// <param name="e"></param>

        protected void btnDel_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
for (int i = 0; i < cboFileList.Items.Count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
//删除选中的附件
                if (cboFileList.Items[i].Selected)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
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>");
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 将选中的上传附件的Id和名称保存到隐藏的控件中。
        
/// </summary>

        protected void SetValueName()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            hidValue.Value 
= "";
            hidName.Value 
= "";
            
for (int i = 0; i < cboFileList.Items.Count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
if (String.IsNullOrEmpty(hidValue.Value.Trim()))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    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
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    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脚本调用代码:

 

ContractedBlock.gif ExpandedBlockStart.gif Code

//附件上传
//
IdControl:存放附件Id的控件Id,如:<asp:HiddenField ID="HiddenField1" runat="server" />
//
NameControl:存放附件的链接地址:如:<div id="divFile" style="width:50px;height:50px"></div>
function FileUpLoad(IdControl,NameControl)
ExpandedBlockStart.gifContractedBlock.gif
{
     
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;
     
ExpandedSubBlockStart.gifContractedSubBlock.gif     ret
=window.showModalDialog(encodeURI(url),{doc:document,win:parent},"dialogWidth:"+sWidth+"px;dialogHeight:"+sHeight+"px;resizable:0");
}

附件下载页面:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
ExpandedBlockStart.gifContractedBlock.gif<%@ Page Language="C#" %>
ExpandedBlockStart.gifContractedBlock.gif
<script runat="server">
protected 
void Page_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
if (Request.QueryString["ID"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            string id 
= Request["ID"].ToString();

            YKSoft.OA.Model.Common.ComTAttachments info 
= (new YKSoft.OA.BLL.Common.ComTAttachments()).GetItem(id);
            
            
if (info != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                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>

 

这样我们就可以在需要附件上传的页面调用该功能了,测试页如下:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
ExpandedBlockStart.gifContractedBlock.gif<%@ 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>
     
<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>

 

源码:http://files.cnblogs.com/yknb/Attachment.rar

转载于:https://www.cnblogs.com/yknb/archive/2008/09/03/1282611.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
检测指定目录是否存在, 检测指定文件是否存在, 如果存在则返回true, 获取指定目录中所有文件列表,获取指定目录中所有子目录列表, 取指定目录及子目录中所有文件列表, 指定目录的绝对路径,检测指定目录是否为空, 检测指定目录中是否存在指定的文件, 若要搜索子目录请使用重载方法., 检测指定目录中是否存在指定的文件, 创建目录, 删除目录, 创建文件, 移动文件(剪贴--粘贴), 复制文件, 根据时间得到目录名 / 格式:yyyyMMdd 或者 HHmmssff, 根据时间得到文件名HHmmssff, 根据时间获取指定路径的 后缀名的 的所有文件, 复制文件夹,检查文件, 如果文件不存在则创建, 删除指定文件夹对应其他文件夹里的文件, 从文件的绝对路径中获取文件名( 包含扩展名 ), 复制文件参考方法,页面中引用, 创建一个目录, 创建一个文件, 并将字节流写入文件, 获取文本文件的行数, 获取一个文件的长度, 单位为Byte, 获取文件大小并以B,KB,GB,TB, 获取指定目录中的子目录列表, 向文本文件写入内容, 向文本文件的尾部追加内容, 将现有文件的内容复制到新文件中, 将文件移动到指定目录, 从文件的绝对路径中获取文件名( 不包含扩展名 ), 从文件的绝对路径中获取扩展名 以上每一行为一个方法, 例子如下: #region 清空指定目录 /// /// 清空指定目录下所有文件及子目录,但该目录依然保存. /// /// 指定目录的绝对路径 public static void ClearDirectory(string directoryPath) { directoryPath = HttpContext.Current.Server.MapPath(directoryPath); if (IsExistDirectory(directoryPath)) { //删除目录中所有的文件 string[] fileNames = GetFileNames(directoryPath); for (int i = 0; i < fileNames.Length; i++) { DeleteFile(fileNames[i]); } //删除目录中所有的子目录 string[] directoryNames = GetDirectories(directoryPath); for (int i = 0; i < directoryNames.Length; i++) { DeleteDirectory(directoryNames[i]); } } } #endregion #region 清空文件内容 /// /// 清空文件内容 /// /// 文件的绝对路径 public static void ClearFile(string filePath) { //删除文件 File.Delete(filePath); //重新创建该文件 CreateFile(filePath); } #endregion #region 删除指定目录 /// /// 删除指定目录及其所有子目录 /// /// 指定
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值