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. [PHP] 浅谈 Laravel Authentication 的 auth:api

    auth:api 在 Laravel 的 Routing , Middleware , API Authentication 主题中都有出现. 一. 在 Routing 部分可以知道 auth:api ...

  2. spring boot 实现定时任务

    定时任务或者说定时调度,是系统中比较普遍的一个功能,例如数据归档.清理,数据定时同步(非实时),定时收发等等都需要用到定时任务,常见的定时调度框架有Quartz.TBSchedule等. 如何在Spr ...

  3. CSP2019初赛游记

    没想到居然ak了,就纪念一下吧. 这次的联赛,只能说是高三生活的一缕杂音了吧. 这次,我的心态可以说是非常平稳了.毕竟不再会有竞赛生涯的压力,也不会有患得患失的惶恐.不过也许我开考前的放声唱歌惊扰了一 ...

  4. 使用Skywalking分布式链路追踪系统

    使用Skywalking分布式链路追踪系统 https://www.cnblogs.com/sunyuliang/p/11424848.html 当我们用很多服务时,各个服务间的调用关系是怎么样的?各 ...

  5. Google Adsense(谷歌网站联盟)广告申请指南

    Google AdSense 是一种获取收入的快速简便的方法,适合于各种规模的网站发布商.它可以在网站的内容网页上展示相关性较高的 Google 广告,并且这些广告不会过分夸张醒目.由于所展示的广告同 ...

  6. POJ-图论-最短路模板(邻接矩阵)

    POJ-图论-最短路模板 一.Floyd算法 刚读入数据时,G为读入的图邻接矩阵,更新后,G[i][j]表示结点i到结点j的最短路径长度 int G[N][N];//二维数组,其初始值即为该图的邻接矩 ...

  7. JS实现简单的图片透明度循环变化(渐变)

    找了好多,都是由100到0就结束了,到头来自己魔改,以下就是源码. div中加入img,js添加函数,完事(调用),取名后面加个1是为了避免冲突 <!DOCTYPE HTML> <h ...

  8. libevent源码分析二--timeout事件响应

    libevent不仅支持io事件,同时还支持timeout事件与signal事件,这篇文件将分析libevent是如何组织timeout事件以及如何响应timeout事件. 1.  min_heap ...

  9. for循环与if条件语句的复习运用

    鉴于前面学了不少基础了,今天没有学新的内容.boyfriend给我出了几道简单的题目,慢慢的进步中. 1.# 计算1-100之间所有偶数的和 def sum(): sumone = 0 for i i ...

  10. (十一)pdf的构成之文件尾

    件尾部(trailer)如何找到交叉引用表和其他特殊对象 属性: / Size [integer]:指定交叉引用表中的条目数(也计算更新部分中的对象).使用的数字不应是间接参考. / Prev [in ...