使用 FilePond(React 组件)将图像上传到 Flask 服务器

Uploading images to a Flask server using FilePond (React component)

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

所以我显然遇到的问题是后端代码。我已经这样设置了我的服务器,per Flask's docs

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')>)])

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

有人能帮忙吗?

这是一个pastebin for the whole server-side code

谢谢!

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

注意表单的 enctype="multipart/form-data" 属性,没有这个你不能上传文件。

还要注意文件输入的 multiple 属性。这允许客户端 select 多个文件。您需要使用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()