Several ways to store images in MySQL database

Several ways to store images in MySQL database

Usually the pictures uploaded by users need to be saved in the database.

There are generally two solutions:

1. Store the path where the picture is saved in the database;

2. Write the image directly into the database field in the form of a binary data stream.

Here are the specific methods:

1. Save the upload path of the picture to the database:

  string uppath="";//Used to save the image upload path//Get the file name of the uploaded image string fileFullname = this.FileUpload1.FileName;
  //Get the time when the picture was uploaded. Using the time as the name of the picture can prevent the picture from having the same name string dataName = DateTime.Now.ToString("yyyyMMddhhmmss");
  //Get the image file name (without extension)
  string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\\") + 1);
  //Get the image extension string type = fileFullname.Substring(fileFullname.LastIndexOf(".") + 1);
  //Judge whether it is the required formatif (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF")
  {
  //Upload the image to the folder of the specified path this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type);
  //Save the path to a variable, and save the value of the variable to the corresponding field in the database uppath = "~/upload/" + dataName + "." + type;
  }

2. Save the image directly to the database as a binary data stream:

Reference the following namespace:

    using System.Drawing;
  using System.IO;
  using System.Data.SqlClient;
  When designing a database, the corresponding field type in the table is iamge
  save:
  //Picture path string strPath = this.FileUpload1.PostedFile.FileName.ToString ();
  //Read the image FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read);
  BinaryReader br = new BinaryReader(fs);
  byte[] photo = br.ReadBytes((int)fs.Length);
  br.Close();
  fs.Close();
  //Save in SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123");
  string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )"; //Operate database statements and modify SqlCommand as needed myComm = new SqlCommand(strComm, myConn);
  myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length);
  myComm.Parameters["@photoBinary"].Value = photo;
  myConn.Open();
  if (myComm.ExecuteNonQuery() > 0)
  {
  this.Label1.Text = "ok";
  }
  myConn.Close();
  Read:
  ...connect to the database string omitting mycon.Open();
  SqlCommand command = new
  SqlCommand("select stuimage from stuInfo where stuid=107", mycon); //Modify the query statement as needed byte[] image = (byte[])command.ExecuteScalar ();
  //Specify the save path and name of the picture read from the database string strPath = "~/Upload/zhangsan.JPG";
  string strPhotoPath = Server.MapPath(strPath);
  //Save the image file according to the above path and name BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));
  bw.Write(image);
  bw.Close();
  //Display the picture this.Image1.ImageUrl = strPath;
  //These two methods can be flexibly selected according to actual needs.

Summarize

The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. Thank you for your support of 123WORDPRESS.COM. If you want to learn more about this, please check out the following links

You may also be interested in:
  • Should nullable fields in MySQL be set to NULL or NOT NULL?
  • The difference between char, varchar and text field types in MySQL
  • MySQL database migration quickly exports and imports large amounts of data
  • Shell script to operate MySQL database to delete duplicate data
  • MySQL implements a solution similar to Oracle sequence
  • mysql code to implement sequence function
  • Can't connect to local MySQL through socket ''/tmp/mysql.sock'' solution
  • A complete list of commonly used MySQL functions (classified and summarized)
  • Use MySQL master-slave configuration to achieve read-write separation and reduce database pressure
  • MySQL sql_mode analysis and setting explanation

<<:  Virtual Box tutorial diagram of duplicating virtual machines

>>:  jQuery implements form validation

Recommend

Configure Java development environment in Ubuntu 20.04 LTS

Download the Java Development Kit jdk The downloa...

Node+Express test server performance

Table of contents 1 Test Environment 1.1 Server H...

Detailed steps to implement the Excel import function in Vue

1. Front-end-led implementation steps The first s...

Detailed explanation of the process of using GPU in Docker

Table of contents Download tf-gpu Build your own ...

Simple usage of MySQL temporary tables

MySQL temporary tables are very useful when we ne...

Why is the scroll bar on the web page set on the right?

Why are the scroll bars of the browsers and word ...

How does Vue3's dynamic components work?

Table of contents 1. Component Registration 1.1 G...

Javascript uses the integrity attribute for security verification

Table of contents 1. Import files using script ta...

Vue implements a simple shopping cart example

This article example shares the specific code of ...

How to install mysql in docker

I recently deployed Django and didn't want to...

MySQL query syntax summary

Preface: This article mainly introduces the query...

MySQL limit performance analysis and optimization

1. Conclusion Syntax: limit offset, rows Conclusi...

Select web page drop-down list and div layer covering problem

Questions about select elements in HTML have been...