Ignored sqlserver data types-image, sqlserver-image
SqlServerThe data type isImageUsed to store images up2gTo convert the image to binary! The disadvantage is that it occupies a lot of data storage space. However, it is much easier to read and store images for the previously stored physical path.
Then the imageMVCHow is the program stored in the database and displayed from the database to the page:
The following is a simple example:
Private string sqlconn = "Data Source =; Initial Catalog = Image; Persist Security Info = True; User ID = sa; Password = 123456"; // GET: /UpDownload/public ActionResult Index () {return View ();} [HttpPost] [ValidateInput (false)] public bool Upload (HttpPostedFileBase [] fileToUpload) {string path = ""; try {// TODDO: Read the path foreach (HttpPostedFileBase file in fileToUpload) {path = System. IO. path. combine (Server. MapPath ("~ /")," Uploadimage \ "+ System. IO. path. getFileName ("00" + file. fileName. substring (file. fileName. lastIndexOf (". "); // write data to the database file. saveAs (path); // read the image to be stored as a data stream FileStream fs = new FileStream (path, FileMode. open, FileAccess. read); Byte [] imgbtye = new byte [fs. length]; fs. read (imgbtye, 0, Convert. toInt32 (fs. length); fs. close (); using (SqlConnection conn = new SqlConnection (sqlconn) {conn. open (); SqlCommand cmd = new SqlCommand (); cmd. connection = conn; cmd. commandText = "insert into T_TeacherImage (TeacherImage) values (@ imgfile)"; SqlParameter par = new SqlParameter ("@ imgfile", SqlDbType. image); par. value = imgbtye; cmd. parameters. add (par); cmd. executeNonQuery () ;}} return true;} catch {return false ;}# region reads the file and directly displays it in the view public void Read () {byte [] MyData = new byte [0]; using (SqlConnection conn = new SqlConnection (sqlconn) {conn. open (); SqlCommand cmd = new SqlCommand (); cmd. connection = conn; cmd. commandText = "select TeacherImage from T_TeacherImage where id = '1'"; SqlDataReader sdr = cmd. executeReader (); sdr. read (); MyData = (byte []) sdr ["TeacherImage"]; Response. contentType = "image/gif"; Response. binaryWrite (MyData); conn. close () ;}# endregion
Then, how can images be displayed on a webpage? It is very simple:
if (xhr.readyState == 4 && xhr.status == 200) { $('#personimg').attr("src", "http://localhost:55576/UpDownload/Read"); }
The implementation environment of this demo is MVC, and the image retrieval path is: current service host address/controller/action
Sqlserver provides a lot of convenience for reading and writing images!