简体   繁体   中英

Issue with reading file encoding within python-Dash-base64

I am using a dash program within python 3 where in I have a dcc.upload element, trying to upload files in dash. my code looks like below:

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)

On uploading wither a PowerPoint or excel file i have it gives following error:

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

I know its related to my files that I am uploading. How can i solve this error?

Use BytesIO instead of StringIO .

For example change this line

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

to this:

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

See the Upload component example in the documentation for reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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