ASP.NET从数据库上传下载文件


 老是找不到合适的数据库上传下载的,从网上找了一些代码,改写了个可以直接使用的版本!

  代码

  AttachmentId    bigint    Unchecked

  AttachmentName    nvarchar(50)    Unchecked

  AgencyName    nvarchar(50)    Checked

  ClassName    nvarchar(255)    Checked

  TypeName    nvarchar(50)    Checked

  Image    image    Checked

  Flag    int    Checked

  Notes    text    Checked

  Unchecked

  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Attachment.aspx.cs" Inherits="hrootCIS.DataShow.Types.NewNavigator.Attachment" %>

  <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

  <!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">

  <title>附件信息</title>

  <link href ="http://www.cnblogs.com/../Styles/AjaxTookitStyle.css" type="text/css" rel="stylesheet" />

  </head>

  <body>

  <form id="form1" runat="server">

  <div style="height: 1882px; width: 1200px">

  <asp:ScriptManager ID="ScriptManager1" runat="server">

  </asp:ScriptManager>

  <cc1:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0"

  Height="1616px" >

  <cc1:TabPanel runat="server" HeaderText="添加附件信息" ID="TabPanel1">

  <HeaderTemplate>

  添加附件信息

  </HeaderTemplate>

  <ContentTemplate>

  <div>

  <asp:Label ID="lblPoistion" runat="server" Text="附件:"></asp:Label>

  <input id="UpFile" runat="server" name="File1"

  type="file" /><br />

  <br />

  <br />

  <table>

  <tr>

  <td>选择公司:</td>

  <td><asp:DropDownList ID="dplAgencyA" runat="server"

  DataSourceID="SqlDataSourceAgencyA" DataTextField="AgencyName"

  DataValueField="Agencyid"></asp:DropDownList><asp:SqlDataSource ID="SqlDataSourceAgencyA" runat="server"

  ConnectionString="<%$ ConnectionStrings:mvcNewsConnectionString %>"

  SelectCommand="SELECT * FROM [Agency]"></asp:SqlDataSource></td></tr>

  <tr>

  <td>附件所属类别:</td>

  <td> <asp:DropDownList ID="dplClass" runat="server">

  <asp:ListItem>企业研究报告</asp:ListItem>

  <asp:ListItem>广告投放信息</asp:ListItem>

  <asp:ListItem>媒体曝光信息</asp:ListItem>

  <asp:ListItem>行业调研报告</asp:ListItem>

  </asp:DropDownList>

  </td>

  </tr>

  <tr>

  <td>附件简介</td>

  <td>

  <asp:TextBox ID="txtNotes" runat="server" Height="81px" TextMode="MultiLine"

  Width="273px"></asp:TextBox>  </td>

  </tr>

  </table>

  <asp:Button ID="btnUpLoad" runat="server" Text="上传附件"

  onclick="btnUpLoad_Click" />

  </div>

  </ContentTemplate>

  </cc1:TabPanel>

  <cc1:TabPanel ID="TabPanel2" runat="server" HeaderText="管理">

  <HeaderTemplate >

  管理附件信息

  </HeaderTemplate>

  <ContentTemplate >

  <table cellpadding="0" cellspacing="0" style="height: 30px" width="98%"><tr><td><asp:DropDownList ID="DropDownList1" runat="server"

  DataSourceID="SqlDataSourceAgencyB" DataTextField="AgencyName"

  DataValueField="Agencyid"></asp:DropDownList><asp:SqlDataSource ID="SqlDataSourceAgencyB" runat="server"

  ConnectionString="<%$ ConnectionStrings:mvcNewsConnectionString %>"

  SelectCommand="SELECT * FROM [Agency]"></asp:SqlDataSource></td></tr><tr><td>

  <asp:Button

  ID="BtnShowAttachment" runat="server" Text="显示所选公司的附件信息"

  onclick="BtnShowAttachment_Click" BorderStyle="Outset"

  BorderWidth="1px" /></td></tr><tr><td align="center"><asp:GridView ID="gdvAttachment" runat="server" AutoGenerateColumns="False"

  Width="400px" CellPadding="4" ForeColor="#333333" GridLines="None"><AlternatingRowStyle BackColor="White" /><Columns><asp:TemplateField

  HeaderText="ID" Visible="False"><ItemTemplate><asp:Label ID="lblId"

  runat="server" Text="<%#Bind('AttachmentId') %>"></asp:Label></ItemTemplate></asp:TemplateField><asp:TemplateField><ItemTemplate><%#Eval("AttachmentName")%></a></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="选项"><ItemTemplate><asp:CheckBox ID="chkDelete" runat="server" /></ItemTemplate></asp:TemplateField><asp:TemplateField></asp:TemplateField></Columns><EditRowStyle BackColor="#2461BF" /><FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /><HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /><PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /><RowStyle BackColor="#EFF3FB" /><SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /></asp:GridView></td></tr><table><tr><td><asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="删除" /></td></tr></table></table>

  </ContentTemplate>

  </cc1:TabPanel>

  <cc1:TabPanel ID="TabPanel3" runat="server" HeaderText="下载附件">

  <HeaderTemplate >

  下载附件

  </HeaderTemplate>

  <ContentTemplate >

  <asp:GridView ID="gdvAttachmentA" runat="server" AutoGenerateColumns="False"

  DataSourceID="SqlDataSourceAttachment"

  onrowcommand="gdvAttachmentA_RowCommand" DataKeyNames="AttachmentId">

  <Columns >

  <asp:BoundField DataField="AttachmentName" HeaderText="文件名称"

  SortExpression="AttachmentName" />

  <asp:BoundField DataField="ClassName" HeaderText="ClassName"

  SortExpression="ClassName" />

  <asp:TemplateField>

  <ItemTemplate>

  <asp:LinkButton ID="lbtnDownload" runat="server" CommandName="download" CommandArgument='<%#Eval("AttachmentName") %>'>下载</asp:LinkButton>

  </ItemTemplate>

  </asp:TemplateField>

  </Columns>

  </asp:GridView>

  <asp:SqlDataSource ID="SqlDataSourceAttachment" runat="server"

  ConnectionString="<%$ ConnectionStrings:mvcNewsConnectionString %>"

  SelectCommand="SELECT AttachmentId,AttachmentName,ClassName FROM [Attachment]"></asp:SqlDataSource>

  </ContentTemplate>

  </cc1:TabPanel>

  </cc1:TabContainer>

  </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 System.Data;

  using System.Configuration;

  using System.Collections;

  using System.Web.Security;

  using System.Web.UI.WebControls.WebParts;

  using System.Web.UI.HtmlControls;

  using System.IO;

  using System.Web.SessionState;

  using System.Drawing;

  using System.Data.SqlClient;

  using hrootCIS.DataCollection;

  namespace hrootCIS.DataShow.Types.NewNavigator

  {

  public partial class Attachment : System.Web.UI.Page

  {

  string constring = ConfigurationManager.ConnectionStrings["connectionString"].ToString();

  protected void Page_Load(object sender, EventArgs e)

  {

  }

  protected void btnUpLoad_Click(object sender, EventArgs e)

  {

  //文件名称

  string path = this.UpFile.PostedFile.FileName;

  string filename = path.Substring(path.LastIndexOf("\\") + 1);

  //文件大小

  int size = this.UpFile.PostedFile.ContentLength;

  //文件类型

  string type = this.UpFile.PostedFile.ContentType;

  Response.Write("path=" + path + "<br/>filename=" + filename + "size=" + size + ",type=" + type);

  //if (!(type == "image/gif" || type == "image/pjpeg" || type == "image/bmp"))

  //    Response.Write("<script language='javascript'>alert('请上传附件格式');</script>");

  //else

  // {

  try

  {

  Stream ImageStream = UpFile.PostedFile.InputStream;

  byte[] Content = new byte[size];

  int Status = ImageStream.Read(Content, 0, size);

  AttachmentInfo info = new AttachmentInfo();

  info.AttachmentName = filename;

  info.AgencyName = this.dplAgencyA.SelectedItem.Text;

  info.ClassName = this.dplClass.SelectedItem.Text;

  info.TypeName = type;

  info.Image = Content;

  info.Flag = 0;

  info.Notes = this.txtNotes.Text;

  AttachmentToData.AddAttachment(info);

  Response.Write("<br/><font color=\"green\" size=\"4\">上传成功</font>");

  }

  catch (Exception ex)

  {

  Response.Write(ex.ToString());

  Response.Write("<script language='javascript'>alert('请不要给同一个企业上传同名附件');</script>");

  }

  // }

  }

  protected void BtnShowAttachment_Click(object sender, EventArgs e)

  {

  BindGrivdView();

  }

  protected void btnDelete_Click(object sender, EventArgs e)

  {

  foreach (GridViewRow row in this.gdvAttachment.Rows)

  {

  if (((CheckBox)row.FindControl("chkDelete")).Checked)

  {

  int id = int.Parse(((Label)row.FindControl("lblId")).Text);

  this.BulletinDelete(id);

  }

  }

  BindGrivdView();

  }

  protected void BulletinDelete(int id)

  {

  //Response.Write("id=" + id);

  AttachmentToData.DeleteAttachmentById(id);

  }

  /// <summary>

  /// 根据所选择的公司名称 显示出相关的签约信息

  /// </summary>

  protected void BindGrivdView()

  {

  List<AttachmentInfo> myMeida = AttachmentToData.GetAttachmentListByAgencyName(this.dplAgencyA.SelectedItem.Text);

  this.gdvAttachment.DataSource = myMeida;

  this.gdvAttachment.DataBind();

  }

  protected void gdvAttachmentA_RowCommand(object sender, GridViewCommandEventArgs e)

  {

  if (e.CommandName == "download")

  {

  byte[] fileData = null;

  using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))

  {

  SqlCommand cmd = new SqlCommand("select Image from Attachment where AttachmentId = @AttachmentId", cn);

  int index = ((e.CommandSource as LinkButton).NamingContainer as GridViewRow).RowIndex;

  cmd.Parameters.AddWithValue("@AttachmentId", gdvAttachmentA.DataKeys[index].Value);

  cn.Open();

  fileData = cmd.ExecuteScalar() as byte[];

  }

  if (fileData == null)

  {

  Response.StatusCode = 404;

  }

  else

  {

  //使用Content-Disposition会有些缺点,在不同的浏览器中文件名显示有些不正常,如果用FireFox就无须编码

  Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(e.CommandArgument.ToString(), System.Text.Encoding.UTF8) + "\"");

  Response.BinaryWrite(fileData);

  }

  Response.End();

  }

  }

  }

  }

 



相关阅读:
用JavaScript计算字符串占用字节数
了解Linux系统内核安全的入侵侦察系统
Js之软键盘实现(js源码)
Linux操作系统中的文件管理技巧
IE Firefox在css中的差别 (部分)
jquery 单击li防止重复加载的实现代码
js 数组的for循环到底应该怎么写?
Jquery数独游戏解析(一)-页面布局
模拟抽奖
在chrome中window.onload事件的一些问题
ssh 命令说明
PHP 中英文混合排版中处理字符串常用的函数
[CGI]检测是否为https连接
MySQL数据库配置技巧
快速导航

Copyright © 2016 phpStudy |