【问题标题】:Python - Flask image upload failing without errorPython - Flask 图像上传失败且没有错误
【发布时间】:2022-02-19 07:22:11
【问题描述】:

我将以下数据发布到我的烧瓶图像上传服务器。问题是图像没有被保存。控制台没有错误。

我已经尝试解码图像字节,它似乎是一个格式正确的多部分请求。

那为什么图片不能正常上传呢?

import os
from flask import Flask, flash, request, redirect, url_for, send_from_directory
import sys

UPLOAD_FOLDER = '/Users/admin/Desktop/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

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

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        print(request.get_data(), file=sys.stdout)
        # 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 an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
            return redirect(url_for('uploaded_file',
                                    filename=file.filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


if __name__ == "__main__":
    # Quick test configuration. Please use proper Flask configuration options
    # in production settings, and use a separate file or environment variables
    # to manage the secret key!
    app.secret_key = 'super secret key'
    app.config['SESSION_TYPE'] = 'filesystem'

    # sess.init_app(app)

    app.debug = True
    app.run()

数据即时发布:(我使用位于代码中的print(request.get_data(), file=sys.stdout) 捕获它)

https://pastecode.io/s/cpev4ny4

【问题讨论】:

    标签: python flask multipartform-data


    【解决方案1】:

    您能否验证您的 apache 或您使用的任何东西是否有权在该目录中写入(保存图像)?

    【讨论】:

    • 是的,当我在首页使用图片上传时效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多