当前位置: 首页 > news >正文

Asp.net 中文件以Binary 形式数据库的保存和读取

Asp.net 中文件以Binary 形式数据库的保存和读取

数据表部分

前台- File_upload.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="File_Upload.aspx.cs" Inherits="File_Upload" %>

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

<script language="JavaScript">

function addFile()

{

var str = '<INPUT type="file" size="50" NAME="File">'

document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)

}

</script>

</head>

<body>

<form id="form2" method="post" runat="server" enctype="multipart/form-data">

<div align="center">

<h3>多文件上传</h3>

<P id="MyFile"><INPUT type="file" size="50" NAME="File"></P>

<P>

<input type="button" value="增加(Add)" onclick="addFile()">

<input onclick="this.form.reset()" type="button" value="重置(ReSet)">

<asp:Button Runat="server" Text="开始上传" ID="Button1" OnClick="UploadButton_Click"></asp:Button>

</P>

<P>

<asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt"

Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>

</P>

<br />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="335px" OnRowCommand="Gridview_RowCommand">

<Columns>

<asp:BoundField DataField="ID" HeaderText="ID" />

<asp:BoundField DataField="Name" />

<asp:ButtonField ButtonType="Image" CommandName="Download" HeaderText="Download" ImageUrl="~/images/mailto.gif"

Text="Download" />

</Columns>

</asp:GridView>

</div>

</form>

</body>

</HTML>

后台:File_Upload.aspx.cs

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

using System.Data.Sql;

using System.Data.SqlClient;

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

{

private string connString;

private void InitalDB()

{

string uid = System.Configuration.ConfigurationManager.AppSettings.Get("uid");

string pwd = System.Configuration.ConfigurationManager.AppSettings.Get("pwd");

string server = System.Configuration.ConfigurationManager.AppSettings.Get("server");

string database = System.Configuration.ConfigurationManager.AppSettings.Get("database");

connString = "Server=" + server + ";uid=" + uid + ";pwd=" + pwd + ";database=" + database;

}

protected void Page_Load(object sender, EventArgs e)

{

InitalDB();

BindData();

}

protected void UploadButton_Click(object sender, EventArgs e)

{

///'遍历File表单元素

HttpFileCollection files = HttpContext.Current.Request.Files;

/// '状态信息

System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

strMsg.Append("上传的文件分别是:<hr color=red>");

try

{

for (int iFile = 0; iFile < files.Count; iFile++)

{

///'检查文件扩展名字

HttpPostedFile postedFile = files[iFile];

string fileName, fileExtension;

fileName = System.IO.Path.GetFileName(postedFile.FileName);

if (fileName != "")

{

fileExtension = System.IO.Path.GetExtension(fileName);

strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");

strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");

strMsg.Append("上传文件的文件名:" + fileName + "<br>");

strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");

///'可根据扩展名字的不同保存到不同的文件夹

///注意:可能要修改你的文件夹的匿名写入权限。

///

FileStream fs = new FileStream(postedFile.FileName, FileMode.Open, FileAccess.Read);

BinaryReader br = new BinaryReader(fs);

byte[] bytes = br.ReadBytes((int)fs.Length);

br.Close();

fs.Close();

SqlConnection myConn = new SqlConnection(connString);

string strComm = "insert into tb_files(name,File_Data,File_Size)values('" + fileName + "',@FileBinary, '" + fileName.Length + "')";

SqlCommand myComm = new SqlCommand(strComm, myConn);

myComm.Parameters.Add("@FileBinary", SqlDbType.Image);

myComm.Parameters["@FileBinary"].Value = bytes;

myConn.Open();

myComm.ExecuteNonQuery();

myConn.Close();

//postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName);

}

}

strStatus.Text = strMsg.ToString();

}

catch (System.Exception Ex)

{

strStatus.Text = Ex.Message;

}

}

private void BindData()

{

DataTable dt = new DataTable();

SqlConnection myConn = new SqlConnection(connString);

string sql = "select id,name,File_Size from tb_files ";

myConn.Open();

SqlDataAdapter adp=new SqlDataAdapter(sql,myConn);

adp.Fill(dt);

GridView1.DataSource = dt;

GridView1.DataBind();

}

protected void Gridview_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName == "Download")

{

DataTable dt = new DataTable();

SqlConnection myConn = new SqlConnection(connString);

string sql = "select id,name,File_Size,file_data from tb_files where id='9' ";

myConn.Open();

SqlDataAdapter adp = new SqlDataAdapter(sql, myConn);

adp.Fill(dt);

if (dt.Rows.Count > 0)

{

Response.Buffer = true;

Response.Clear();

Response.ContentType = "application/x-msexcel";

Response.BinaryWrite((byte[])dt.Rows[0]["file_data"]);

}

}

}

}

---Result---

相关文章:

  • [LeetCode]—Permutations 求全排列
  • [LeetCode]—Permutations II 求全排列(有重复值)
  • 动态装卸DLL示例-匪徒和
  • 一个困扰我一个多星期的Nebula3的BUG
  • [Python]—Linux Server 系统监控程序
  • .NET 4.0中使用内存映射文件实现进程通讯
  • 中国移动短信指令大全
  • SQLServer中的循环批处理
  • IT市场10大趋势!
  • 关于Oracel 10g http://ip:1158/em 的问题
  • 18句话入门SQLServer XML
  • 移动商务潜力无穷
  • 一道可以成为.NET面试“必杀题”的“简单问题”
  • Linux 简单的网络配置练习一
  • 解决Ubuntu 9.04 耳机有声音但外放无声问题
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • 2017-08-04 前端日报
  • Android开发 - 掌握ConstraintLayout(四)创建基本约束
  • avalon2.2的VM生成过程
  • Cumulo 的 ClojureScript 模块已经成型
  • Map集合、散列表、红黑树介绍
  • PyCharm搭建GO开发环境(GO语言学习第1课)
  • python 装饰器(一)
  • vue 个人积累(使用工具,组件)
  • webpack项目中使用grunt监听文件变动自动打包编译
  • windows下mongoDB的环境配置
  • 对话:中国为什么有前途/ 写给中国的经济学
  • 给Prometheus造假数据的方法
  • 机器学习 vs. 深度学习
  • 基于Javascript, Springboot的管理系统报表查询页面代码设计
  • 基于webpack 的 vue 多页架构
  • 力扣(LeetCode)965
  • 马上搞懂 GeoJSON
  • 如何优雅地使用 Sublime Text
  • 深入浏览器事件循环的本质
  • 通过几道题目学习二叉搜索树
  • 想写好前端,先练好内功
  • 用jQuery怎么做到前后端分离
  • mysql面试题分组并合并列
  • 京东物流联手山西图灵打造智能供应链,让阅读更有趣 ...
  • 数据库巡检项
  • ​LeetCode解法汇总1410. HTML 实体解析器
  • ​直流电和交流电有什么区别为什么这个时候又要变成直流电呢?交流转换到直流(整流器)直流变交流(逆变器)​
  • #我与Java虚拟机的故事#连载16:打开Java世界大门的钥匙
  • $.ajax()方法详解
  • $var=htmlencode(“‘);alert(‘2“); 的个人理解
  • (2)MFC+openGL单文档框架glFrame
  • (delphi11最新学习资料) Object Pascal 学习笔记---第8章第5节(封闭类和Final方法)
  • (ibm)Java 语言的 XPath API
  • (react踩过的坑)Antd Select(设置了labelInValue)在FormItem中initialValue的问题
  • (附源码)spring boot火车票售卖系统 毕业设计 211004
  • (太强大了) - Linux 性能监控、测试、优化工具
  • (一)u-boot-nand.bin的下载
  • (转)真正的中国天气api接口xml,json(求加精) ...
  • .bat批处理(四):路径相关%cd%和%~dp0的区别