繁体   English   中英

在 python-Dash-base64 中读取文件编码的问题

[英]Issue with reading file encoding within python-Dash-base64

我在 python 3 中使用了一个破折号程序,其中我有一个 dcc.upload 元素,试图在破折号中上传文件。 我的代码如下所示:

upload = html.Div([html.Label('Upload file'),
    dcc.Upload(
        id='upload-templ',
        children=html.Div(['Drag and Drop or ',html.A('Select Files')]),
        style={
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        # Allow multiple files to be uploaded
        multiple=True
    ),
    html.Div(id='data-upload')])

def parse_contents(contents, filename, date):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'xlsx' in filename:
            # Assume that the user uploaded a CSV file
            wb = openpyxl.load_workbook(io.StringIO(decoded.decode('utf8')))
            ws = wb["sheet"]
            all_rows = list(ws.rows)
                        
            return html.Div([
            'its excell'
        ])
            
        elif 'temp' in filename:
            pptFilepath = io.StringIO(decoded.decode('utf8'))
            return html.Div([
            'its powerpoint'
        ])
            
            # Assume that the user uploaded an excel file
            #df = pd.read_excel(io.BytesIO(decoded))
    except Exception as e:
        print(e)

在上传 PowerPoint 或 excel 文件时,我有以下错误:

Powerpoint: 'utf-8' codec can't decode byte 0xca in position 15: invalid continuation byte
Excel: 'utf-8' codec can't decode byte 0xb2 in position 14: invalid start byte

我知道它与我上传的文件有关。 我该如何解决这个错误?

使用BytesIO而不是StringIO

例如改变这一行

wb = openpyxl.load_workbook(io.StringIO(decoded.decode('utf8')))

对此:

wb = openpyxl.load_workbook(io.BytesIO(decoded))

请参阅文档中Upload组件示例以供参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM