程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#寫入和讀取圖片(c# asp.net sqlserver)

C#寫入和讀取圖片(c# asp.net sqlserver)

編輯:關於C#
 

首先要創建一個表包含自段image 和 type 類型各自為image 和 vnanchar

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="ReadAndWritePicFromDB.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <FONT face="宋體"><INPUT id="File1" style="Z-INDEX: 101; LEFT: 112px; POSITION: absolute; TOP: 88px" type="file" name="File1" runat="server"></FONT> <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 400px; POSITION: absolute; TOP: 88px" runat="server" Text="Write" Width="104px"></asp:Button> <asp:Button id="Button2" style="Z-INDEX: 103; LEFT: 552px; POSITION: absolute; TOP: 88px" runat="server" Text="Read" Width="105px"></asp:Button> </form> </body> </HTML>

 

WebForm1.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;

namespace ReadAndWritePicFromDB
{
/// <summary>
/// WebForm1 的摘要說明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile File1;
protected System.Web.UI.WebControls.Button Button1;
private string fileName = "" ;
protected System.Web.UI.WebControls.Button Button2;
private static SqlConnection conn = null;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置用戶代碼以初始化頁面
ConnectDB();
}

//得到文件名
private string GetFile()
{
HttpPostedFile file = File1.PostedFile;
fileName = file.FileName;

return fileName;
}

//讀取文件內容
private byte[] ReadFile()
{
FileStream file = File.OpenRead(GetFile());
byte[] content = new byte[file.Length];
file.Read(content,0,content.Length);
file.Close();

return content;
}

//連接數據庫
private void ConnectDB()
{
string connStr = "Initial Catalog=;Data Source=;User ID=;Password=;";
conn = new SqlConnection(connStr);
conn.Open();
}

//寫入圖片到數據庫中
private void WriteImage()
{
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "insert into images(image,type) values(@image,@type)";
comm.CommandType = CommandType.Text;
SqlParameter param = comm.Parameters.Add("@image",SqlDbType.Image);
param.Value = ReadFile();
param = comm.Parameters.Add("@type",SqlDbType.NVarChar);
param.Value = GetContentType(new FileInfo(fileName).Extension.Remove(0,1));

if(comm.ExecuteNonQuery() == 1)
Response.Write("Successful");
else
Response.Write("Fail");

conn.Close();
}

//獲取圖片的後綴名
private string GetContentType(string extension)
{
string type = "";

if(extension.Equals("jpg") || extension.Equals("JPG"))
type = "jpeg";
else
type = extension;

return "image/"+type;
}

//從數據庫中讀取圖片
private void ReadImage()
{
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "select image,type from images";
comm.CommandType = CommandType.Text;

SqlDataReader reader = comm.ExecuteReader();
while(reader.Read())
{
Response.ContentType = reader["type"].ToString();//讀寫類型 一定要設置 否則浏覽器會當作文本輸出
Response.BinaryWrite((byte[])reader["image"]);//圖片數據
}

Response.Write("Successful");
Response.End();

conn.Close();
}
#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
WriteImage();
}

private void Button2_Click(object sender, System.EventArgs e)
{
try
{
ReadImage();
}
catch(Exception ep)
{
conn.Close();
Response.End();
}
}
}
}
 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved