如何使用flask API保存图像,然后将其返回到我的React应用程序以使用它

2024-09-28 05:17:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用我的FlaskAPI将图像保存到数据库或文件系统中,但这是我从未做过的事情,而且没有任何进展

我希望能够在调用路由时返回图像,并且能够在我的ReactJS应用程序中使用它,只需使用一个img标记

我所能找到的就是如何将图像保存到数据库中,然后使用路由下载它。我需要能够归还它。(它不是我所需要的。)

这就是当时的情况:

    @app.route('/img-upload', methods=['POST'])
def img_upload():
    file = request.files['image']

    newFile = Mealplan(name=file.filename, data=file.read())

    db.session.add(newFile)
    db.session.commit()

    return jsonify({"Done!" : "The file has been uploaded."})

@app.route('/get-mealplan-image/<given_mealplan_id>')
def download_img(given_mealplan_id):
    file_data = MealPlan.query.filter_by(id=given_mealplan_id).first()
    return send_file(BytesIO(file_data.data), attachment_filename=file_data.name, as_attachment=True)

Tags: 图像imageid数据库app路由imgdata
1条回答
网友
1楼 · 发布于 2024-09-28 05:17:01

在文件系统上保存文件将是一种更合适的方法。下面是一个简单的例子:

from flask import send_from_directory

basedir = os.path.abspath(os.path.dirname(__file__))
uploads_path = os.path.join(basedir, 'uploads')  # assume you have created a uploads folder


@app.route('/img-upload', methods=['POST'])
def upload_image():

    f = request.files['image']
    f.save(os.path.join(uploads_path , f.filename))  # save the file into the uploads folder

    newFile = Mealplan(name=f.filename)  # only save the filename to database
    db.session.add(newFile)
    db.session.commit()

    return jsonify({"Done!" : "The file has been uploaded."})


@app.route('/images/<path:filename>')
def serve_image(filename):
    return send_from_directory(uploads_path, filename)  # return the image

在React应用程序中,您可以使用文件名生成图像URL:/images/hello.jpg

更新:

如果您只能获取id,则查看功能将类似:

@app.route('/get-mealplan-image/<given_mealplan_id>')
def download_img(given_mealplan_id):
    file_data = MealPlan.query.filter_by(id=given_mealplan_id).first()
    return send_from_directory(uploads_path, file_data.name)

相关问题 更多 >

    热门问题