C# 保存文件到数据库

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>
View Code

后台代码

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");
        }
    }
}
View Code

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 
";
                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 > 0)
                        {
                            byte[] fileBytes = (byte[])dt.Rows[0]["FileBytes"];
                            string fileName = dt.Rows[0]["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;
            }
        }
    }
}
View Code

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]
View Code
原文地址:https://www.cnblogs.com/lidaying5/p/11545560.html