1

我有一个本地托管的 Flask 服务器和一个小型 React 应用程序。我正在尝试使用FilePond作为图像上传的简单解决方案。FilePond 负责将每个图像发送到服务器。

所以我显然遇到的问题是后端代码。根据 Flask 的文档,我已经像这样设置了我的服务器

UPLOAD_FOLDER='/images'
ALLOWED_EXTENSIONS = set(['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():
print(request.files)
    if request.method == "POST":
        # check if the post request has the file part
        if 'file' not in request.files:
            print('No file part')
            return make_response("No File Part", 400)
        file = request.files["file"]
        # if user does not select file, browser also submit an empty part
        # without filename
        if file.filename == '':
            print('No selected file')
            return make_response("No Selected File", 400)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename) # filenames can be dangerous!
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return make_response("Success", 201)

然而,当放一个

 print(request.files)

upload_file() 函数开头的语句,似乎这是服务器正在接收的请求:

ImmutableMultiDict([('images', <FileStorage: 'imageName.jpg' ('image/jpeg')>)])

我不知道如何处理。我不知道“图像”是否应该是“文件”的位置。我只是不确定从这里去哪里或如何处理接收到的数据。我不知道是什么,我从未见过使用 <> 语法。

任何人都可以帮忙吗?

这是整个服务器端代码的 pastebin

谢谢!

4

1 回答 1

0

这是一个概念验证应用程序,可让您使用表单上传多个图像:

请注意enctype="multipart/form-data"表单的属性,否则您将无法上传文件。

还要注意multiple文件输入的属性。这允许客户端选择多个文件。您需要使用request.files.getlist()来获取所有上传文件的列表。

一旦生成了保存文件的路径,保存werkzeug.FileStorage对象就是调用它的.save(path_to_save)方法。

from flask import Flask, request, render_template_string, redirect, abort
from werkzeug import secure_filename
from pathlib import Path

UPLOAD_DIR: Path = Path(__file__).parent / 'uploads'
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)

app = Flask(__name__)


def is_valid_upload(upload) -> bool:
    # some validation logic
    return Path(upload.filename).suffix.lower() in ['.jpg', '.jpeg']


@app.route('/', methods=['GET', 'POST'])
def upload():
    html = '''
        <form action='/' method='POST' enctype="multipart/form-data">
            <input type="file" name='images' multiple>
            <button>Upload</button>
        </form>
    '''

    if request.method == 'GET':
        return html

    uploaded_files = request.files.getlist('images')
    if not uploaded_files or not uploaded_files[0].filename:
        return redirect('/')

    valid_uploads = list(filter(is_valid_upload, uploaded_files))
    if not valid_uploads:
        return 'invalid image(s)', 400

    for upload in valid_uploads:
        filename = secure_filename(upload.filename)
        save_path = str(UPLOAD_DIR / filename)

        upload.save(save_path)

    return 'uploaded'


if __name__ == "__main__":
    app.run()
于 2019-07-05T22:42:06.190 回答