We can save any type of file to SQL Server, before performing an example, set the test form, 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] Gocreate Table [DBO]. [Testfiles] ([ID] [
int
Identity
1
,
1
) NOT NULL, [MyFileName] [varchar]
50
) Collate chinese_prc_ci_as not null, [fileType] [varchar]
50
) Collate chinese_prc_ci_as not null, [myfile] [Image] not null) on [primary] textImage_on [primary] Go
Create up to the uplist below:
Once the form is submitted, we use the HTMLINPUTFILE class's postedFile property to access the files we upload, use the properties and methods of the HTTPPostedFile class to read, save upload files, and get other information for upload files. Here we don't use the SaveAs method because it is used to save the file. We have to save the data into the database, we use the InputStream property, which is used to initialize the stream to read our data. At the same time, we use ContentLength to read the file size, and ContentType reads the file type. Then create a BYTE array, save the file stream into this array, and save it to the database.
Here 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)
{// get the submitted file stream filedatastream = myfile.postedfile.inputStream; // Get file size int filelength = myfile.postedfile.contentLength; // Create an array byte [] fileData = new byte [filength]; // Put the file stream Fill to the array FileDataStream.read (FileData, 0, FileLength); // Get file name string filetitle = myfilename.value; // Get file type string filetype = myfile.postedFile.conteType; // Build database connection, SQL statement, create parameter SqlConnection connection = new SqlConnection ( "Server = .; uid = sa; pwd =; Database = 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); // play Open, execute the query connection.open (); command.executenonquery (); connection.close (); message.text = "Your file has been successfully uploaded"; MyFileName.Value = "";} script>