Flask:从请求中获取多个表单文件

问题描述

我有一个在flask 中运行的python 应用程序,我需要从一个post 请求中读取多个png 图像。

首先,您可以在这里看到我尝试尝试的请求(标​​题为:application/x-www-form-urlencoded 作为内容类型):

my request

我想要从我的烧瓶应用程序中获取每个 png 文件的二进制数据,将它们存档在 tar 文件中并上传到存储中。重要提示:我事先不知道我会收到多少这样的文件

关于文档 (https://flask.palletsprojects.com/en/1.1.x/api/#flask.Request) 我尝试了不同的东西,但没有找到一个好的和简单的方法获取这个二进制数据。例如我尝试:

dict_data = dict(request.form)
print(dict_data)

返回给我类似的东西:

 {'------WebKitFormBoundaryfQXWRsfmCXS0xGpU\r\nContent-disposition: form-data; name':'"file1"; filename="1.png"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00�\x00\x00\x00�\x08\x06\x00\x00\x00�>a�\x00\x00 \x00IDATx^�{~#In��� ��k�7����\x7f�m���\x7f_\x04P�EQR�4�3�v�d��DVF\x06�\x00\x128���]_��]\x7f�LJ/\x0f\x00�9\x08\x1e\x00x\x00���\x7f�\x07\x03<\x00p�W��?��\x01\x1e\x00�� p�\x1f��\x00\x0f\x00��\x15���`�\x07\x00��\n���\x7f0�\x03\x00w~\x05���?\x18�\x01�;�\x02w��\x1f\x0c�\x00��_�;��\x0f\x06x\x00���\x7f�\x07\x03<\x00p�W��?��\x01\x1e\x00�� p�\x1f��\x00\x0f\x00��\x15���`�\x07\x00��\n���\x7f0�\x03\x00w~\x05���?\x18�\x01�;�\x02w��\x1f\x0c�\x00��_�;�
...
0f<)\x04\x00�����\x7f\x06E��\x08�[�n\x00\x00\x00\x00IEND�B`�\r\n------       WebKitFormBoundaryfQXWRsfmCXS0xGpU--\r\n': ''}

那是不可能解析的。 相同的结果:

request.form

返回:

ImmutableMultiDict([('------WebKitFormBoundaryYGznFIzweAgRIB3P\r\nContent-disposition: form-data; name','"file1"; filename="1.png"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00�\x00\x00\x00�\x08\x06\x00\x00\x00�>a�\x00\x00 \x00IDATx^�{~#In��� ��k�7����\x7f�m���\x7f_\x04P�EQR�4�3�v�d��DVF\x06�\x00\x128���]_��]\x7f�LJ/\x0f\x00�9\x08\x1e\x00x\x00���\x7f�\x07\x03<\x00p�W��?��\x01\x1e\x00�� p�\x1f��\x00\x0f\x00��\x15���`�\x07\x00��\n��
...
Q\x06�/涮��\\>��c{\x05�D\x01)��r�EH��_<',''),('\t� ��v\x05\x00\x00���J��\x18���6\x15�a\x00�\x03�\x0f<)\x04\x00�����\x7f\x06E��\x08�[�n\x00\x00\x00\x00IEND�B`�\r\n------WebKitFormBoundaryYGznFIzweAgRIB3P--\r\n','')])

为了

request.files

我只有:

 ImmutableMultiDict([]) 

我只是想要一个简单的方法来拥有类似的东西:

{'file1': binary_data_of_1.png,'file2': binary_data_of_2.png}

在 python 中是否有一种简单的方法

谢谢

解决方法

如果你真的想要每个文件的二进制数据:

@app.route("/upload",methods=["POST"])
def upload():
    binary_data = {}
    the_files = request.files
    for file in the_files:
        binary_data[file] = the_files[file].read()
    ...

对象 the_files[file] 的类型为 werkzeug.datastructures.FileStorage

请参阅 Request.Files 文档 here

参见 FileStorage here 的数据结构