Save and output images in SQL Server

xiaoxiao2021-03-05  27

In SQL Server stored and output images Author: cashcho (translated www.ASPCool.com time: 2002-2-2 12:09:24 Reads: 56724

Introduction Sometimes we need to save some Binary Data into the database. SQL Server provides a special data type called Image for us to save Binary Data. Binary Data can be a picture, a document, and more. In this article we will see how to save and output pictures in SQL Server. Jian Table In order to test this example you need a Table containing data (you can create it in the current library, you can also create a new database), below is its structure: Column name DataType Purpose ID Integer Identity Column Primary Key Imgtitle Varchar (50) Stores some user friendly title to identity the image IMGTYPE Varchar (50) Stores image content type. This will be same as recognized content types of ASP.NET IMGDATA Image Stores actual image or binary data. save images into the SQL Server database In order to save pictures to Table, you first get from the client to your web server. You can create a web form, get the title of the picture with TextBox, get a picture file with HTML File Server Control. Confident, you set the form's EncType property for Multipart / Form-Data.

Stream imgdatastream = File1.PostedFile.InputStream; int imgdatalen = File1.PostedFile.ContentLength; string imgtype = File1.PostedFile.ContentType; string imgtitle = TextBox1.Text; byte [] imgdata = new byte [imgdatalen]; int n = imgdatastream. Read (imgdata, 0, imgdatalen); string connstr = ((NameValueCollection) Context.GetConfig ( "appSettings")) [ "connstr"]; SqlConnection connection = new SqlConnection (connstr); SqlCommand command = new SqlCommand ( "INSERT INTO ImageStore (imgtitle, imgtype, imgdata) VALUES (@imgtitle, @ imgtype, @ imgdata) ", connection); SqlParameter paramTitle = new SqlParameter (" @imgtitle ", SqlDbType.VarChar, 50); paramTitle.Value = imgtitle; command.Parameters .Add (paramTitle); SqlParameter paramData = new SqlParameter ( "@imgdata", SqlDbType.Image); paramData.Value = imgdata; command.Parameters.Add (paramData); SqlParameter paramType = new SqlParam eter ( "@imgtype", SqlDbType.VarChar, 50); paramType.Value = imgtype; command.Parameters.Add (paramType); connection.Open (); int numRowsAffected = command.ExecuteNonQuery (); connection.Close (); Output from the database Now let's take out our just saved in the database, where we will output pictures to the browser. You can also save it as a file or do anything you want to do.

转载请注明原文地址:https://www.9cbs.com/read-33575.html

New Post(0)