小编seg*_*.py的帖子

为什么string.encode('utf-8')!= bytes(map(ord,string))是真的吗?

我们考虑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);
}
Run Code Online (Sandbox Code Playgroud)

我的视图收到如下数据:

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))
Run Code Online (Sandbox Code Playgroud)

我检查过,contents在JS代码和Python代码中都是一样的.它们具有相同的字节长度,并且似乎具有相同的内容,通过适合我的屏幕的第一个和最后几个字符来判断.

如果我将我的代码更改为

def upload(request):
    contents = …
Run Code Online (Sandbox Code Playgroud)

python encoding bytearray utf-8 python-3.x

1
推荐指数
1
解决办法
165
查看次数

标签 统计

bytearray ×1

encoding ×1

python ×1

python-3.x ×1

utf-8 ×1