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

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

问题描述

我必须在我的项目目录的静态文件夹中上传一些图片,但我不知道如何对我的代码说。在下面的code.py我能够上传一个图像,并将其存储在相同级别的静态文件夹的项目目录中,但我会认为这个图像可以存储INSIDE静态文件夹。

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

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

我要做什么?谢谢你们

解决方案

您需要定义上传文件夹



文档

  import os $ b $ from flask flask从werkzeug.utils导入烧瓶,请求,重定向,url_for 
导入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':
#检查post请求是否有文件部分
如果文件不在request.files中:
flash('No file part')
return redirect(request.url)$ b $ file = request.files [文件']
#如果用户没有选择文件,浏览器也
#提交一个没有文件名的空白部分
如果文件(file.filename):
文件名=安全文件名(file.filename)
file.save(os.path.join(app.config ['UPLOAD_FOLDER'],filename))

http://flask.pocoo。 org / docs / 0.12 / patterns / fileuploads /

所以你的代码是 UPLOAD_FOLDER ='/ path / to / static /图片或类似的东西


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

解决方案

you need to define the upload folder

from the flask documentation

import os
from flask import Flask, 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))

http://flask.pocoo.org/docs/0.12/patterns/fileuploads/

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

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

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