Save and output any type of file in SQL Server

zhaozj2021-02-11  179

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]') And ObjectProperty (ID, n'susertable ') = 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, [fileetype] [varchar] (50) collate chinese_prc_ci_as not null, [Myfile] 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 name "%>" system.data "%> <% @ import namespace =" system.data.sqlclient " %>