首页 > 解决方案 > 如何在 Python 中从 btoa(unescape(encodeURIComponent(file))) 解码 utf-8 文件?

问题描述

我想将带有 HTML 文件输入的任何文件(Word、PDF、图像...)上传到 python 服务器。
在snakecharmerb(将文件作为JSON上传到Python网络服务器)的帮助下,我可以通过在JavaScript中以下列方式编码来发送文件:

function fileChange(event) {
    const file = event.target.files[0];
    const fileReader = new FileReader();
    fileReader.onload = function(e) {
        const encodedFile = btoa(unescape(encodeURIComponent(e.target.result)));
        uploadFile(JSON.stringify(encodedFile), file.name);
    }
    fileReader.readAsText(file);
}

在 Python 中,我可以通过以下方式读取和保存文件:

import json
from base64 import b64decode

binary_data = b64decode(json.loads(file));
with open(file_name, "wb") as f:
    f.write(binary_data)

但生成的文件不可读或内容编码不正确。我想我需要在 utf-8 中编码 binary_data。但是binary_data.encode("utf-8")会导致错误。

test_file.txt

Hello World!
Special chars: äöüß

Python 错误

UnicodeDecodeError('ascii', 'Hello World!\r\nSpecial chars: \xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd', 29, 30, 'ordinal not in range(128)')

我也尝试将它与.decode('string_escape')

标签: javascriptpythonutf-8decodeencode

解决方案


推荐阅读