在 Flask 中上传图片 [英] Upload image in Flask

查看:34
本文介绍了在 Flask 中上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在我的项目目录的静态文件夹中上传一些图片,但我不知道如何对我的代码说出来.在下面的 code.py 中,我可以上传图像并将其存储在与静态文件夹相同级别的项目目录中,但我希望该图像可以存储在静态文件夹中.

I have to upload some images in static folder of my project directory, but i don't know how to say it to my code. In the follow code.py i'm able to upload an image and store it in the project directory at the same level of static folder, but i would that this image can be store INSIDE static folder.

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']

      f.save(secure_filename(f.filename))
      return render_template('end.html')

我该怎么办??谢谢各位

What i have to do?? Thanks guys

推荐答案

需要定义上传文件夹

来自 flask 文档

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

所以你的代码应该是 UPLOAD_FOLDER = '/path/to/static/images' 或者类似的东西

So your code would be UPLOAD_FOLDER = '/path/to/static/images' or something like that

这篇关于在 Flask 中上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆