【发布时间】:2014-10-06 20:03:21
【问题描述】:
我们认为bytes(map(ord, string)) 使用的是什么编码?为什么string.encode('utf-8') != bytes(map(ord, string)) 有时是真的?
我在让客户端 javascript 与 Django 1.5 (Python 3) 应用程序交互时遇到了这个问题。
基本上,我使用 ajax 和 jDataView 将 mp3 文件作为字符串上传(我找不到直接上传文件的解决方案)。我使用 jDataView 将文件转换为字符串。在我的 Django 应用程序中,当我保存文件时,它会更改大小。但是,如果我不使用string.encode('utf-8') 而不是使用bytes(map(ord, string)),则文件保存得很好。这是为什么?为什么是string.encode('utf-8') != bytes(map(ord, string))?
我的客户端代码如下所示:
function send(file) {
var reader = new FileReader();
reader.onload = function(event) {
var self = this;
$.ajax({
url: 'upload/',
type: 'POST'
data: {contents: (new jDataView(self.result)).getString()}
});
}
reader.readAsArrayBuffer(file);
}
我的视图接收数据如下:
def upload(request):
contents = request.POST.get('contents')
track = Track.objects.all[0] # For testing only
contents = bytes(map(ord, contents))
track.file.save('file.mp3', ContentFile(contents))
我检查了 JS 代码和 Python 代码中的 contents 是一回事。它们具有相同的字节长度,并且从适合我屏幕的第一个和最后几个字符来看似乎具有相同的内容。
如果我将代码更改为
def upload(request):
contents = request.POST.get('contents')
track = Track.objects.all[0] # For testing only
contents = contents.encoding('utf-8')
track.file.save('file.mp3', ContentFile(contents))
文件大小改变,不再是有效的 mp3 文件。
【问题讨论】:
标签: python python-3.x encoding utf-8 bytearray