Copy Code code as follows:
Using System;
Using System.Collections;
Using System.Configuration;
Using System.Data;
Using System.Linq;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.HtmlControls;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Data.SqlClient;
Using System.IO;
Namespace Delegate
{
public partial class ReadStream:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
}
<summary>
Convert uploaded files to binary stream save in database
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
protected void Button1_Click (object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection (configurationmanager.connectionstrings["SQL"). ToString ());
String strsql= "INSERT into Test (timage) VALUES (@images)"//The way in which the binary stream is stored requires the form of a parameter
SqlCommand cmd = new SqlCommand (strSQL, conn);
Conn. Open ();
string filepath = Server.MapPath ("~/");
filepath + = Fileupload1.filename;
Fileupload1.saveas (filepath);
FileStream fs = new FileStream (filepath, FileMode.Open, FileAccess.Read);//Read files
BinaryReader br = new BinaryReader (FS);
byte[] Photo = Br. readbytes (int) fs. Length);
Br. Close ();
Fs. Close ();
Cmd. Parameters.Add ("@images", sqldbtype.binary, photo. LENGTH);//Set parameters
Cmd. parameters["@images"]. Value = photo;//Set values
if (cmd. ExecuteNonQuery () = = 1)
{
Response.Write ("Add success!") ");
}
Conn. Close ();
}
protected void button2_click (object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection (configurationmanager.connectionstrings["SQL"). ToString ());
Conn. Open ();
String strSQL = "SELECT top 1 timage from Test";
SqlCommand cmd = new SqlCommand (strSQL, conn);
SqlDataReader dr = cmd. ExecuteReader (commandbehavior.closeconnection);
if (Dr. Read ())
{
Byte[] by = (byte[]) dr[0];
Response.AddHeader ("Content-disposition", "attachment; Filename=ceshi.txt ");/Set Read headers
Response.AddHeader ("Content-length", by. Length.tostring ());
Response.ContentType = "Text/plain";//Set Output type This can be saved in the database dynamically implemented types
Response.OutputStream.Write (by, 0, by. Length); Output
Response.Flush ();
}
Conn. Close ();
}
}
}