Save and output files of any type in SQL Server

Source: Internet
Author: User
Tags array eval file size
Server we can save any type of file to SQL Server, and before we do that, we'll set up a test table, Testfile.sql:

if exists (SELECT * from dbo.sysobjects WHERE id = object_id (N ' [dbo].[ TestFiles] ')
and OBJECTPROPERTY (ID, N ' isusertable ') = 1)
drop table [dbo]. [TestFiles]
Go

CREATE TABLE [dbo]. [TestFiles] (
[ID] [int] IDENTITY (1, 1) not NULL,
[myFileName] [varchar] (m) COLLATE chinese_prc_ci_as not NULL,
[FileType] [varchar] (m) COLLATE chinese_prc_ci_as not NULL,
[MyFile] [Image] Not NULL
) on [PRIMARY] textimage_on [PRIMARY]
Go

Create an upload form below:

Once the form is submitted, we use the PostedFile property of the HtmlInputFile class to access the file we uploaded, using the properties and methods of the Httppostedfile class to read, save the uploaded file, and obtain additional information about the uploaded file. Here we do not use the SaveAs method, because it is used to save the file. We're going to save the data to the database, we use the InputStream property, and it's used to initialize the stream to read our data. At the same time, we use ContentLength to read the file size, contenttype read the file type. It then creates a byte array, saves the file stream into the array, and then saves it to the database.

The following is the complete code "CS version" uploadfile.aspx:

<% @Page language= "C #"%>
<% @Import namespace= "System.IO"%>
<% @ Import namespace= "System.Data"%>
<% @ Import namespace= "System.Data.SqlClient"%>

<script runat= "Server" >
public void Uploadbtn_click (Object sender, EventArgs e) {

Documents submitted
Stream filedatastream = MyFile.PostedFile.InputStream;

Get File size
int filelength = MyFile.PostedFile.ContentLength;

Create an array
byte[] Filedata = new Byte[filelength];

To populate a file stream with an array
Filedatastream.read (filedata,0,filelength);

Get the file name
string filetitle = Myfilename.value;

Get file type
string fileType = MyFile.PostedFile.ContentType;

Building database connections, SQL statements, creating parameters
SqlConnection connection = new SqlConnection ("server=.; uid=sa;pwd=;D atabase=testuploadfile ");
SqlCommand command = new SqlCommand (INSERT into TestFiles (myfilename,myfile,filetype) +
"VALUES (@MyFileName, @MyFile, @FileType)", connection);

SqlParameter paramtitle = new SqlParameter ("@MyFileName", sqldbtype.varchar,35);
Paramtitle.value = Filetitle;
Command. Parameters.Add (Paramtitle);

SqlParameter paramdata = new SqlParameter ("@MyFile", sqldbtype.image);
Paramdata.value = Filedata;
Command. Parameters.Add (Paramdata);

SqlParameter paramtype = new SqlParameter ("@FileType", sqldbtype.varchar,25);
Paramtype.value = FileType;
Command. Parameters.Add (Paramtype);

Open connection, execute query
Connection. Open ();
Command. ExecuteNonQuery ();
Connection. Close ();

message.text= "Your file has been successfully uploaded";
Myfilename.value = "";
}
</script>
<asp:label id= "Message" text= "Select File and file name:" runat= "Server"/>
<form method= "POST" enctype= "Multipart/form-data" runat= "Server" >
<b> file name: </b><input id= "myFileName" type= "text" runat= "Server" >
<P>
<b> files: </b><input id= "MyFile" type= "file" runat= "Server" >
<br><br>
<input type=submit value= "Start uploading" onserverclick= "Uploadbtn_click" runat= "Server" >
</form>

Once we have uploaded successfully, we can browse the file: Just set the MIME type of the page and then output it with the BinaryWrite () of the response object.

Showuploadfile.aspx

<% @Page language= "C #"%>
<% @Import namespace= "System.IO"%>
<% @ Import namespace= "System.Data"%>
<% @ Import namespace= "System.Data.SqlClient"%>
<script runat= "Server" >
private void Page_Load (Object sender, EventArgs e) {
String Sql= "SELECT * from TestFiles";
SqlConnection connection = new SqlConnection ("server=.; uid=sa;pwd=;D atabase=testuploadfile ");
SqlCommand command = new SqlCommand (sql, connection);
Connection. Open ();
Filelist.datasource = command. ExecuteReader ();
Filelist.databind ();
Connection. Close ();
}
</script>

<form runat= "Server" >
<asp:datagrid id= "filelist" runat= "Server"
Bordercolor= "Orange" borderwidth= "2" cellpadding= "4"
Autogeneratecolumns= "false" showheader= "true" align= "center" >
Font-bold= "True" font-size= "9" horizontalalign= "Center"/>
<Columns>
<asp:templatecolumn headertext= "file name" >
<ItemTemplate>
<b>
<%# DataBinder.Eval (Container.DataItem, "myFileName")%>
</b>
</ItemTemplate>
</asp:TemplateColumn>
<asp:templatecolumn headertext= "Type" >
<ItemTemplate>
<b>
<%# DataBinder.Eval (Container.DataItem, "FileType")%>
</b>
</ItemTemplate>
</asp:TemplateColumn>

<asp:templatecolumn headertext= "View" >
<ItemTemplate>
<b>
<a href= "showfile.aspx?id=<%# databinder.eval (Container.DataItem, ' ID ')%>" > View file </a>
</b>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>

Showfile.aspx

<% @Page language= "C #"%>
<% @Import namespace= "System.IO"%>
<% @ Import namespace= "System.Data"%>
<% @ Import namespace= "System.Data.SqlClient"%>
<script runat= "Server" >
private void Page_Load (Object sender, EventArgs e) {
String Sql= "select * from testfiles WHERE id = '" + request.querystring["id" + "'";
SqlConnection connection = new SqlConnection ("server=.; uid=sa;pwd=;D atabase=testuploadfile ");
SqlCommand command = new SqlCommand (sql, connection);
Connection. Open ();
SqlDataReader dr = command. ExecuteReader ();
if (Dr. Read ()) {
Response.Clear ();
Response.AddHeader ("Content-type", dr["FileType"). ToString ());
Response.BinaryWrite ((byte[]) dr["MyFile");
}
Dr. Close ();
Connection. Close ();
}
</script>

Also need to note is: to exe,zip files and so on further processing, in order to directly download.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.