在软件开发中,将图像附加到文件夹或数据库中是常见的需求,具体选择哪种方式取决于应用场景和需求。以下是关于这两种方法的详细解释:
将图像文件直接存储在服务器的文件系统中,并在数据库中存储图像文件的路径。
from flask import Flask, render_template, request, redirect, url_for
import os
app = Flask(__name__)
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# 将文件名保存到数据库
return redirect(url_for('uploaded_file', filename=filename))
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return render_template('uploaded.html', filename=filename)
if __name__ == '__main__':
app.run(debug=True)
将图像文件以二进制形式存储在数据库中,而不是存储文件路径。
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///images.db'
db = SQLAlchemy(app)
class Image(db.Model):
id = db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(80), nullable=False)
data = db.Column(db.LargeBinary, nullable=False)
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file:
filename = secure_filename(file.filename)
image_data = file.read()
new_image = Image(filename=filename, data=image_data)
db.session.add(new_image)
db.session.commit()
return redirect(url_for('uploaded_file', filename=filename))
@app.route('/uploads/<filename>')
def uploaded_file(filename):
image = Image.query.filter_by(filename=filename).first()
if image:
return render_template('uploaded.html', image=image)
return "Image not found", 404
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
BLOB
或LONGBLOB
。通过以上解释和示例代码,您可以更好地理解在文件夹或数据库中附加图像的不同方法及其应用场景。
领取专属 10元无门槛券
手把手带您无忧上云