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

Introduction to NFS service construction under Centos7

Table of contents 1. Server 2. Client 3. Testing ...

4 ways to optimize MySQL queries for millions of data

Table of contents 1. The reason why the limit is ...

How to use JavaScript to determine several common browsers through userAgent

Preface Usually when making h5 pages, you need to...

How to create a Docker repository using Nexus

The warehouse created using the official Docker R...

MySQL InnoDB MRR Optimization Guide

Preface MRR is the abbreviation of Multi-Range Re...

Steps to install MySQL 8.0.23 under Centos7 (beginner level)

First, let me briefly introduce what MySQL is; In...

Specific use of GNU Parallel

what is it? GNU Parallel is a shell tool for exec...

Nginx implements https website configuration code example

https base port 443. It is used for something cal...

Disable input text box input implementation properties

Today I want to summarize several very useful HTML...

In-depth interpretation of /etc/fstab file in Linux system

Preface [root@localhost ~]# cat /etc/fstab # # /e...

A small collection of html Meta tags

<Head>……</head> indicates the file he...

Detailed explanation of props and context parameters of SetUp function in Vue3

1. The first parameter props of the setUp functio...

The implementation of Youda's new petite-vue

Table of contents Preface Introduction Live Easy ...