C#从数据库中上传下载附件功能

Page代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo1.aspx.cs" Inherits="order.Demo.Demo1" %>

<!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>Demo1</title>
    <script type="text/javascript" src="../js/jquery-1.6.2.min.js"></script>
    <script type="text/javascript" src="../js/Global.js"></script>
    <script type="text/javascript" src="../js/Calendar.js"></script>
    <link type="text/css" rel="Stylesheet" href="../css/Default.css" />
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" 
        CellPadding="3" GridLines="Horizontal" Width="100%" 
        onrowdatabound="GridView1_RowDataBound" 
        onrowcommand="GridView1_RowCommand" CssClass="text">
        <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
        <Columns>
            <asp:TemplateField HeaderText="选择">
                <ItemTemplate>
                    <input ID="RadioLine" name="RadioLine" type="radio" value="<%#Eval("accessory_id")%>" />
                </ItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
            </asp:TemplateField>
            <asp:BoundField DataField="accessory_id" HeaderText="附件ID" />
            <asp:BoundField DataField="order_header_id" HeaderText="订单ID" />
            <asp:BoundField DataField="accessory_name" HeaderText="附件名称" />
            <asp:BoundField DataField="accessory_description" HeaderText="附件说明" />
            <asp:BoundField DataField="creation_date" DataFormatString="{0:d}" HeaderText="创建日期" />
            <asp:BoundField DataField="created_by" HeaderText="创建人" />
            <asp:BoundField DataField="accessory_size" HeaderText="文件大小" />
            <asp:BoundField DataField="accessory_type" HeaderText="文件类型" />
            <asp:ButtonField CommandName="DownItem" HeaderText="下载" ShowHeader="True" Text="下载" >
            <ItemStyle HorizontalAlign="Center" />
            </asp:ButtonField>
            <asp:ButtonField CommandName="DelItem" HeaderText="删除" ShowHeader="True" Text="删除" >
            <ItemStyle HorizontalAlign="Center" />
            </asp:ButtonField>
        </Columns>
        <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
        <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
        <AlternatingRowStyle BackColor="#F7F7F7" />
    </asp:GridView>
    <asp:FileUpload ID="FileUpload1" runat="server" ToolTip="附件上传" />
    <asp:Button ID="BtnUpload" runat="server" Text="上传" OnClick="BtnUpload_Files"  />
    <input type="hidden" id="hidden_id" runat=server/> 
    </form>
</body>
</html>

<script language="javascript" type="text/javascript">
    // 注销
    function fn_DelItem(cellstring) {
        if (!confirm("确定要删除附件吗?")) {
            return false;
        }
        return true;
    }

    // 注销
    function fn_DownItem(cellstring) {
        return true;
    }

</script>

 C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;
using System.Data.OracleClient;
using order.Components;
using order.commons;

namespace order.Demo
{
    public partial class Demo1 : System.Web.UI.Page
    {
        private Database db = new Database();

        protected void Page_Load(object sender, EventArgs e)
        {
            // 注册单选按钮
            if (!this.IsStartupScriptRegistered("Startup"))
            {
                this.RegisterStartupScript("Startup", RegisterScript.RadioRowSelected(hidden_id.ClientID));
            }
            if(!Page.IsPostBack)
            { 
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.Append("select oa.accessory_id, oa.order_header_id, oa.accessory_name,oa.accessory_description, ");
                sqlBuilder.Append("oa.creation_date, oa.created_by, oa.accessory_size, oa.accessory_type ");
                sqlBuilder.Append("from oe_accessories oa ");
                sqlBuilder.Append("where 1 = 1 ");
                DataSet ds = db.returnds(sqlBuilder.ToString());
                this.GridView1.DataSource = ds.Tables[0].DefaultView;
                this.GridView1.DataBind();
            }
        }

        /// <summary>
        /// 测试上传文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnUpload_Files(object sender, EventArgs e)
        {
            string fileName = "";// 文件名
            string filePath = "";// 文件路径
            string fileType = "";// 文件类型
            string accessory_id = "";
            int fileSize = 0; // 文件大小
            Stream fis;// 上传文件流
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.Append("insert into oe_accessories oa ( ");
            sqlBuilder.Append("accessory_id,order_header_id,accessory_name,accessory_description, ");
            sqlBuilder.Append("accessory_data,creation_date,created_by,oa.accessory_size,oa.accessory_type ) ");
            sqlBuilder.Append("values( ");
            sqlBuilder.Append(":accessory_id,:order_header_id,:accessory_name,:accessory_description, ");
            sqlBuilder.Append(":accessory_data,:creation_date,:created_by,:accessory_size,:accessory_type ) ");
            // 设置参数
            OracleParameter[] orclParams = new OracleParameter[]
            {
                new OracleParameter("accessory_id", OracleType.VarChar),
                new OracleParameter("order_header_id", OracleType.VarChar),
                new OracleParameter("accessory_name", OracleType.VarChar),
                new OracleParameter("accessory_description", OracleType.VarChar),
                new OracleParameter("accessory_data", OracleType.Blob),
                new OracleParameter("creation_date", OracleType.DateTime),
                new OracleParameter("created_by", OracleType.VarChar),
                new OracleParameter("accessory_size", OracleType.Int32),
                new OracleParameter("accessory_type", OracleType.VarChar)
            };
            HttpFileCollection hfc = Request.Files;// 获取上载文件集合
            // 循环获取单个上载文件
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc.Get(i);
                fileName = Path.GetFileName(hpf.FileName);
                filePath = Path.GetDirectoryName(hpf.FileName);
                fileType = Path.GetExtension(hpf.FileName).ToLower();
                fileName = fileName.Substring(0, (fileName.LastIndexOf(".")));
                // 获取文件流大小
                fileSize = hpf.ContentLength;
                if (fileSize < 1)
                {
                    return;
                } 
                // 声明等长byte数组
                byte[] buffers = new byte[fileSize];
                // 获取文件流
                fis = hpf.InputStream;
                // 文件保存到缓存
                fis.Read(buffers, 0, fileSize);
                accessory_id = db.SequencesGenerator("SEQ_OE_ACCESSORIES");
                orclParams[0].Value = accessory_id;
                orclParams[1].Value = "";
                orclParams[2].Value = fileName;
                orclParams[3].Value = fileName;
                orclParams[4].Value = buffers;
                orclParams[4].Size = buffers.Length;
                orclParams[5].Value = DateTime.Now.ToShortDateString();
                orclParams[6].Value = "";
                orclParams[7].Value = fileSize;
                orclParams[8].Value = fileType;
                db.RunOracleCommand(sqlBuilder.ToString(), orclParams);
                MessageBox msg = new MessageBox(this);
                msg.Show("文件上传成功!");
                msg.RefreshUrl("../Demo/Demo1.aspx");
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            // 改变背景颜色
            if (e.Row.RowType == DataControlRowType.Header)
            {
                //
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onclick", "fn_RadioRowSingle(this,event)");
                e.Row.Attributes.Add("class", e.Row.RowIndex % 2 == 0 ? "rowOdd" : "rowEven");
                e.Row.Attributes.Add("oldClass", e.Row.RowIndex % 2 == 0 ? "rowOdd" : "rowEven");
                e.Row.Attributes.Add("onmouseover", "lastBackgroundColor=this.className;this.className='rowCurrent'");
                e.Row.Attributes.Add("onmouseout", "this.className=lastBackgroundColor;");
                // 绑定按钮
                int CellsCount = e.Row.Cells.Count;
                LinkButton BtnDownItem = e.Row.Cells[CellsCount - 2].Controls[0] as LinkButton;
                LinkButton BtnDelItem = e.Row.Cells[CellsCount - 1].Controls[0] as LinkButton;
                string RowCells = "role_id=" + e.Row.Cells[1].Text.Trim();
                BtnDownItem.Attributes.Add("onclick", "return fn_DownItem('" + RowCells + "');");
                BtnDelItem.Attributes.Add("onclick", "return fn_DelItem('" + RowCells + "');");
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // 删除
            if (e.CommandName == "DelItem")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = this.GridView1.Rows[index];
                string accessory_id = row.Cells[1].Text.Trim();
                List<String> BatchSQL = new List<String>();
                string newSQL = "delete from oe_accessories oa where 1 = 1 and oa.accessory_id = '" + accessory_id + "' ";
                BatchSQL.Add(newSQL);
                db.RunOracleCommandBatch(BatchSQL);
                MessageBox msg = new MessageBox(this);
                msg.Show("文件删除成功!");
                msg.RefreshUrl("../Demo/Demo1.aspx");
            }
            // 下载-直接下载文件流
            if (e.CommandName == "DownItemTest")
            {
                try
                {
                    int index = Convert.ToInt32(e.CommandArgument);
                    GridViewRow row = this.GridView1.Rows[index];
                    string accessory_id = row.Cells[1].Text.Trim();
                    // 取出后写到一个文件中
                    FileStream fos;
                    // 以二进制形式将基元类型写入流
                    BinaryWriter writer;
                    int bufferSize = 1024;
                    // 该字节的BLOB缓冲区,以填补getbytes 
                    byte[] bytes = new byte[bufferSize];
                    long retval;
                    long startIndex = 0;
                    string fileName = "";
                    StringBuilder sqlBuilder = new StringBuilder();
                    sqlBuilder.Append("select oa.accessory_name,oa.accessory_data from oe_accessories oa where 1 = 1 and oa.accessory_id ='").Append(accessory_id).Append("' ");
                    OracleDataReader dr = db.returndr(sqlBuilder.ToString());
                    while (dr.Read())
                    { 
                        // 读文件名
                        fileName = dr["accessory_name"].ToString();
                        // 创建一个文件
                        fos = new FileStream(Path.GetTempPath() + fileName, FileMode.OpenOrCreate, FileAccess.Write);
                        writer = new BinaryWriter(fos);
                        startIndex = 0;
                        retval = dr.GetBytes(1, startIndex, bytes, 0, bufferSize);
                        while (retval == bufferSize)
                        {
                            writer.Write(bytes);
                            writer.Flush();
                            startIndex += bufferSize;
                            retval = dr.GetBytes(1, startIndex, bytes, 0, bufferSize);
                        }
                        writer.Write(bytes, 0, (int)retval);
                        writer.Flush();
                        // 释放资源
                        writer.Close();
                        fos.Close();
                    }
                }
                catch (Exception ex)
                {
                    order.SystemError.SystemLog(ex.Message);
                }
                finally
                {
                    db.Close();
                }
            }
            // 下载-显示打开和保存
            if (e.CommandName == "DownItem")
            {
                try
                {
                    int index = Convert.ToInt32(e.CommandArgument);
                    GridViewRow row = this.GridView1.Rows[index];
                    string accessory_id = row.Cells[1].Text.Trim();
                    // 取出后写到一个文件中
                    FileStream fos;
                    // 以二进制形式将基元类型写入流
                    BinaryWriter writer;
                    int fileSize = 1024;
                    long retval;
                    long startIndex = 0;
                    string fileName = "";
                    string fileType = "";
                    StringBuilder sqlBuilder = new StringBuilder();
                    sqlBuilder.Append("select oa.accessory_name,oa.accessory_data,oa.accessory_size,oa.accessory_type ");
                    sqlBuilder.Append("from oe_accessories oa where 1 = 1 and oa.accessory_id ='").Append(accessory_id).Append("' ");
                    OracleDataReader dr = db.returndr(sqlBuilder.ToString());
                    while (dr.Read())
                    {
                        // 读文件名
                        fileName = dr["accessory_name"].ToString();
                        fileSize = int.Parse(dr["accessory_size"].ToString());
                        fileType = dr["accessory_type"].ToString();
                        // 该字节的BLOB缓冲区,以填补getbytes 
                        byte[] bytes = new byte[fileSize];
                        // 创建一个文件
                        fos = new FileStream(Path.GetTempPath() + fileName, FileMode.OpenOrCreate, FileAccess.Write);
                        writer = new BinaryWriter(fos);
                        startIndex = 0;
                        retval = dr.GetBytes(1, startIndex, bytes, 0, fileSize);
                        while (retval == fileSize)
                        {
                            writer.Write(bytes);
                            writer.Flush();
                            startIndex += fileSize;
                            retval = dr.GetBytes(1, startIndex, bytes, 0, fileSize);
                        }
                        writer.Write(bytes, 0, (int)retval);
                        writer.Flush();
                        // 释放资源
                        writer.Close();
                        fos.Close();
                        this.Response.Clear();
                        Response.ClearHeaders();
                        Response.Buffer = false;
                        string ct = this.DownFile_ContentType(fileType);
                        Response.ContentType = ct;
                        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                        Response.AppendHeader("Content-Length", bytes.Length.ToString());
                        Response.BinaryWrite(bytes); //二进制文件
                        Response.Flush();
                        Response.End();
                    }
                }
                catch (Exception ex)
                {
                    order.SystemError.SystemLog(ex.Message);
                }
                finally
                {
                    db.Close();
                }
            }
        }
        
        /// <summary>
        /// 下载文件类型
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        protected string DownFile_ContentType(string fileType)
        {
            string result = "";
            try
            {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.Append("select pc.type_description from params_codelist pc ");
                sqlBuilder.Append("where 1 = 1 ");
                sqlBuilder.Append("and pc.kind_code = 'CONTENT_TYPE' ");
                sqlBuilder.Append("and pc.type_value = '").Append(fileType).Append("' ");
                OracleDataReader dr = db.returndr(sqlBuilder.ToString());
                while (dr.Read())
                {
                    result = dr["type_description"].ToString().Trim();
                }
                
            }
            catch (Exception ex)
            {
                order.SystemError.SystemLog(ex.Message);
            }
            finally
            {
                db.Close();
            }
            if(result.Length <= 0 )
            {
                result = "text/plain";
            }
            return result;
        }
    }
}

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值