CopyCode The Code is 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 the uploaded file into a binary stream and save it in the database
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Protected void button#click (Object sender, eventargs E)
{
Sqlconnection conn = new sqlconnection (configurationmanager. connectionstrings ["SQL"]. tostring ());
String strsql = "insert into test (timage) values (@ images)"; // The parameter format required to save the binary stream
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 an object
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 the Parameter
Cmd. Parameters ["@ images"]. value = photo; // set the value.
If (CMD. executenonquery () = 1)
{
Response. Write ("added successfully! ");
}
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; filenamecesceshi.txt"); // you can specify the file header.
Response. addheader ("Content-Length", by. length. tostring ());
Response. contenttype = "text/plain"; // set the output type, which can be dynamically implemented in the database.
Response. outputstream. Write (by, 0, by. Length); // output
Response. Flush ();
}
Conn. Close ();
}
}
}