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. sqlserver 创建分区表

    我们知道很多事情都存在一个分治的思想,同样的道理我们也可以用到数据表上,当一个表很大很大的时候,我们就会想到将表拆 分成很多小表,查询的时候就到各个小表去查,最后进行汇总返回给调用方来加速我们的查询速 ...

  2. nginx yaf需要注意的问题

    nginx yaf需要注意的问题 显示视图的方法<pre> $this->getView()->assign(array('pack'=>$return['pack'], ...

  3. 在使用Hanlp配置自定义词典时遇到的问题

    要使用hanlp加载自定义词典可以通过修改配置文件hanlp.properties来实现.要注意的点是: 1. root根路径的配置: hanlp.properties中配置如下: #本配置文件中的路 ...

  4. C++ 智能指针 boost::scoped_ptr分析

    1.scoped_ptr的实现原理及特性 特性:scoped_ptr和auto_ptr类似,但最大的区别就是不能转让管理权限,也就是说scoped_ptr禁止用户进行拷贝和赋值 实现原理:如何才能禁止 ...

  5. Tarjan求有向图强连通分量 BY:优少

    Tarjan算法:一种由Robert Tarjan提出的求解有向图强连通分量的线性时间的算法. 定义给出之后,让我们进入算法的学习... [情境引入] [HAOI2006受欢迎的牛] 题目描述: 每头 ...

  6. expect——通过编写自动化脚本实现信息交互(整理)

    本文简要介绍了expect工具语言的功能.用法,并以实例来具体说明 expect是什么 Expect是一个免费的编程工具语言,用来完成通信过程中的交互式任务,而无需人的干预. 通过shell虽然可以实 ...

  7. 【题解】Luogu P5358 [SDOI2019]快速查询

    原题传送门 神鱼说这道题是强制离线(smog 我们珂以把被单点修改,单点查询的点单独拿出来处理,把每个数表示成\(mul*x+plus\) 初始状态下\(mul=1,plus=0\) 操作1:在总和中 ...

  8. cas sso 单点登录

    一些介绍: https://www.jianshu.com/p/b7de8e4cf217 https://blog.csdn.net/javaloveiphone/article/details/52 ...

  9. scanf加不加\n?

    近两天用vs2013敲代码碰到的问题 关于scanf小括号中加不加\n的区别 例程序如下所示: 第一个程序: int main(){ ; printf("你会去敲代码吗?(选择1 or 0) ...

  10. java基础 Math

    package cn.mantishell.day08.demo04; /** * java.util.Math类是数学相关的工具类,里面提供类大量的静态方法,完成与数学运算相关的操作 * * pub ...