javascript - 如何在 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')
解决方案
推荐阅读
- django - 如何在 Django 视图中获取隐藏输入字段的值?
- php - 从 CSV 文件创建 php 数组时的非英语语言问题
- javascript - 如何使用来自复杂 JSON Webhook 的 Node JS Cloud Function 写入 Cloud Firestore?
- sql - 版本控制/乐观锁定/乐观并发控制
- react-native - 为 React Native 应用程序(iOS 和 Android)实现 Here SDK 的最佳方式是什么?
- r - 如何从数字创建 *%Year%Week* 序列?
- python - 使用 pyvips 调整到特定的高度和宽度
- reactjs - put 方法不适用于反应 axios api 方法
- c# - 在 RAID0 虚拟磁盘上写入大字节数组
- python - Python:访问第二个父级的实例属性