引言

MySQL存储图片的两种方式

1. 存储图片文件

  • 表结构设计:在创建表时,需要添加一个BLOB类型的字段来存储图片数据。
  CREATE TABLE images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    image LONGBLOB NOT NULL
  );
  • 图片上传:在插入图片数据时,可以使用LOADFILE()函数从本地文件系统读取图片文件。
  INSERT INTO images (name, image) VALUES ('example.jpg', LOADFILE('/path/to/example.jpg'));

注意:LOADFILE()函数要求MySQL服务器对指定路径有读取权限,且该路径必须在MySQL服务器的securefilepriv变量指定的目录中。

2. 存储图片路径

  INSERT INTO images (name, image_path) VALUES ('example.jpg', '/path/to/example.jpg');

图片存取技巧

1. 图片上传

  • 前端上传:使用HTML5的File API实现图片上传。
  <input type="file" id="fileInput" />
  <script>
    document.getElementById('fileInput').addEventListener('change', function(e) {
      const file = e.target.files[0];
      // 处理图片上传逻辑
    });
  </script>
  • 后端处理:在服务器端接收上传的图片文件,并存储到文件系统中。
  from flask import Flask, request
  import os

  app = Flask(__name__)
  upload_folder = 'uploads'

  @app.route('/upload', methods=['POST'])
  def upload_file():
    if 'file' not in request.files:
      return 'No file part'
    file = request.files['file']
    if file.filename == '':
      return 'No selected file'
    if file:
      filename = secure_filename(file.filename)
      file.save(os.path.join(upload_folder, filename))
      return 'File uploaded successfully'

  if __name__ == '__main__':
    app.run()

2. 图片读取

  • 数据库查询:根据图片ID或路径从数据库中查询图片数据。
  SELECT image FROM images WHERE id = 1;
  • 文件系统读取:根据图片路径从文件系统中读取图片文件。
  import os

  def read_image(path):
    with open(path, 'rb') as f:
      return f.read()

总结