Saving and outputting any types of files in SQL Server

Source: Internet
Author: User
We can save any type of files to SQL Server. Before performing an example, we should first create 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] (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 an upload form as follows:
Once the form is submitted, we use the PostedFile attribute of the HtmlInputFile class to access the uploaded file, use the attributes and methods of the HttpPostedFile class to read, save the uploaded file, and obtain other information about the uploaded file. Here we do not use the SaveAs method because it is used to save files. We want to save the data to the database. We use the InputStream attribute, 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 to read the file type. Create a byte array, save the file stream to the array, and then save 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 ){
// Obtain the submitted file
Stream fileDataStream = MyFile. PostedFile. InputStream;
// Get the file size
Int fileLength = MyFile. PostedFile. ContentLength;
// Create an array
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.