html

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUploadDataSource.aspx.cs" Inherits="WebApplication1.FileUploadDataSource" %>

<!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>
<style type ="text/css" >
.fileList li{ margin-bottom :5px;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="upFile" runat="server" />
<asp:Button ID="Button1" runat="server"
Text="上传" onclick="Button1_Click" />
</div>
<div>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="Sqldatasource1">
<HeaderTemplate >
<ul class ="fileList">
</HeaderTemplate>
<ItemTemplate >
<li>
<asp:HyperLink ID="HyperLink1" runat="server" Text ='<%#Eval("FileName")%>' NavigateUrl ='<%#Eval("Id","~/FileHandler.ashx?id={0}") %>'>HyperLink</asp:HyperLink>
</li>
</ItemTemplate>
<FooterTemplate >
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
<asp:sqldatasource ID="Sqldatasource1" runat="server"
ConnectionString="Data Source=localhost;Initial Catalog=test;Integrated Security=True"
ProviderName="System.Data.SqlClient" InsertCommand="insert into Files(FileName,FileBytes)values(@FileName,@FileBytes)"
SelectCommand="SELECT Files.* FROM Files">
<InsertParameters>
<asp:ControlParameter ControlID="upFile" Name="FileName"
PropertyName="FileName" />
<asp:ControlParameter ControlID ="upFile" Name ="FileBytes" PropertyName ="FileBytes" />
</InsertParameters>
</asp:sqldatasource>
</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.IO; namespace WebApplication1
{
public partial class FileUploadDataSource : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } protected void Button1_Click(object sender, EventArgs e)
{
if (upFile.HasFile)
{
if (CheckFileType(upFile.FileName))
Sqldatasource1.Insert();
}
} private bool CheckFileType(string fileName)
{
return (Path.GetExtension(fileName).ToLower() == ".doc" || Path.GetExtension(fileName).ToLower() == ".docx");
}
}
}

FileHandler处理页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data; namespace WebApplication1
{
/// <summary>
/// FileHandler 的摘要说明
/// </summary>
public class FileHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/msword";
string conString = "Data Source=localhost;Initial Catalog=test;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(conString))
{
string sql = "SELECT FileName, FileBytes FROM Files where Id=@id \n";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("@Id", context.Request["Id"]);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count > )
{
byte[] fileBytes = (byte[])dt.Rows[]["FileBytes"];
string fileName = dt.Rows[]["FileName"].ToString();
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
context.Response.BinaryWrite(fileBytes);
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("文件不存在");
}
}
}
} } public bool IsReusable
{
get
{
return false;
}
}
}
}

CREATE TABLE [dbo].[Files](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FileName] [nvarchar](50) NULL,
[FileBytes] [varbinary](max) NULL,
CONSTRAINT [PK_Files] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

C# 保存文件到数据库的更多相关文章

  1. PHP 合理配置实现文件上传及保存文件到数据库

    合理配置 php.ini 如何配置php.ini实现PHP文件上传功能.其中涉及到php.ini配置文件中的upload_tmp_dir.upload_max_filesize.post_max_si ...

  2. PostgreSQL保存文件到数据库

    1.CREATE TABLE public.t_file ( id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval('t_file_id_seq'::regc ...

  3. python保存文件到数据库

    效果 model class WEIGUI_IMG(Base): __tablename__ = 'DW_ZHS_D_WEIGUI_IMG' # 表名 id = Column(), primary_k ...

  4. JAVA上传文件到数据库

    前端代码 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> &l ...

  5. 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)

    1.android下junit测试框架配置 单元测试需要在手机中进行安装测试 (1).在清单文件中manifest节点下配置如下节点 <instrumentation android:name= ...

  6. 小型单文件NoSQL数据库SharpFileDB初步实现

    小型单文件NoSQL数据库SharpFileDB初步实现 我不是数据库方面的专家,不过还是想做一个小型的数据库,算是一种通过mission impossible进行学习锻炼的方式.我知道这是自不量力, ...

  7. redis/分布式文件存储系统/数据库 存储session,解决负载均衡集群中session不一致问题

    先来说下session和cookie的异同 session和cookie不仅仅是一个存放在服务器端,一个存放在客户端那么笼统 session虽然存放在服务器端,但是也需要和客户端相互匹配,试想一个浏览 ...

  8. EXECL文件导入数据库

    Execl数据导入数据库: 注意事项:execl中的列名与列数要与数据库的列名和列数一致.值类型一致,列名不一致的话可在导入的时候,给字段起别名,确定保持一致 v 界面代码: <div> ...

  9. C# ASP.NET CSV文件导入数据库

    原文:C# ASP.NET CSV文件导入数据库 using System; using System.Collections.Generic; using System.Text; using Sy ...

随机推荐

  1. 配置SSH无密码登录【原著】

    环境:两台Centos虚拟机,配置了静态的ip.(详见虚拟机如何配置静态的IP地址的操作步骤) 192.168.75.21192.168.75.22 第一步:为每台服务器配置静态IP地址参见: 虚拟机 ...

  2. CentOS 7.7安装Erlang和Elixir

    安装之前,先看一下它们的简要说明 Erlang Erlang是一种开源编程语言,用于构建对高可用性有要求的大规模可扩展的软实时系统.它通常用于电信,银行,电子商务,计算机电话和即时消息中.Erlang ...

  3. 香农的伟大论文《A Symbolic Analysis of Relay and Switching Circuits》

    香农在1938年发表的伟大论文A Symbolic Analysis of Relay and Switching Circuits(<对继电器和开关电路中的符号分析>)将开关.继电器.二 ...

  4. MyISAM 和 InnoDB 索引的区别

      阅读目录 一 MyISAM索引实现 二 InnoDB索引实现 三 InnoDB索引和MyISAM索引的区别 回到顶部 一 MyISAM索引实现 1. 主键索引 MyISAM引擎使用B+树作为索引结 ...

  5. css3响应式布局教程—css3响应式

    响应式布局 一个网站能够兼容多个终端,并且在各个终端都可以很好展示体验. 媒体类型 在何种设备或者软件上将页面打开 123456789 all:所有媒体braille:盲文触觉设备embossed:盲 ...

  6. 使用matplotlib绘制3D函数图像

    学习并尝试了利用matplotlib进行3D函数图像的绘制 import matplotlib.pyplot as plt # 绘图用的模块 from mpl_toolkits.mplot3d imp ...

  7. Python中NumPy的使用一

    NumPy简介: 一个用python实现的科学计算,包括:1.一个强大的N维数组对象Array:2.比较成熟的(广播)函数库:3.用于整合C/C++和Fortran代码的工具包:4.实用的线性代数.傅 ...

  8. JS Web API 拖拽对话框案例

    <style> .login-header { width: 100%; text-align: right; height: 30px; font-size: 24px; line-he ...

  9. BZOJ5312 冒险 势能分析、线段树

    传送门 区间位赋值.区间求最大值似乎是不能够像一般的线段树一样直接打标记的,但是直接暴力也太没有面子了. 我们考虑优化一下暴力:如果说线段树的一段区间内在当前修改的所有位置上所有数都是相同的,那么这个 ...

  10. ubuntu系统下防火墙简单使用

    apt-get install ufw      安装防火墙sudo ufw enable|disable|status         开启/关闭/查看防火墙状态sudo ufw allow 22/ ...