[英]How to handle uploaded zip file in Dash plotly?
Using the dcc.Upload
, you can build a drag and drop or button-based uploading feature in Dash Plotly dashboard.使用dcc.Upload
,您可以在 Dash Plotly 仪表板中构建拖放或基于按钮的上传功能。 However, there is a limit in the documentation on handling a specific filetype such as .zip
.但是,在处理特定文件类型(例如.zip
的文档中存在限制。 Here's a snippet of the uploading html:这是上传html的片段:
dcc.Upload(
id='upload_prediction',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files'),
' New Predictions (*.zip)'
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
accept=".zip",
multiple=True
)
Then when I try to examine the uploaded file with this snippet:然后,当我尝试使用此代码段检查上传的文件时:
@app.callback(Output('output_uploaded', 'children'),
[Input('upload_prediction', 'contents')],
[State('upload_prediction', 'filename'),
State('upload_prediction', 'last_modified')])
def test_callback(list_of_contents, list_of_names, list_of_dates):
for content in list_of_contents:
print(content)
The content-type after uploading is 'data:application/x-zip-compressed;base64'.上传后的内容类型是'data:application/x-zip-compressed;base64'。 How to handle this type of file in Dash Plotly (for example to extract it somewhere)?如何在 Dash Plotly 中处理此类文件(例如将其提取到某处)?
A similar question was asked in the plotly forum without answers: https://community.plot.ly/t/dcc-upload-zip-file/33976在 plotly 论坛中问了一个类似的问题,没有答案: https ://community.plot.ly/t/dcc-upload-zip-file/33976
Dash Plotly provides the uploaded file in the base64 string format. Dash Plotly 以 base64 字符串格式提供上传的文件。 What you need to do is to decode it first, then handle it as bytes string which later can be used to initialize ZipFile
class (It's a built-in tool in python).您需要做的是首先对其进行解码,然后将其作为字节字符串处理,稍后可用于初始化ZipFile
类(它是 Python 中的内置工具)。
import io
import base64
from zipfile import ZipFile
@app.callback(Output('output_uploaded', 'children'),
[Input('upload_prediction', 'contents')],
[State('upload_prediction', 'filename'),
State('upload_prediction', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
for content, name, date in zip(list_of_contents, list_of_names, list_of_dates):
# the content needs to be split. It contains the type and the real content
content_type, content_string = content.split(',')
# Decode the base64 string
content_decoded = base64.b64decode(content_string)
# Use BytesIO to handle the decoded content
zip_str = io.BytesIO(content_decoded)
# Now you can use ZipFile to take the BytesIO output
zip_obj = ZipFile(zip_str, 'r')
# you can do what you wanna do with the zip object here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.