我們認爲是什麼編碼bytes(map(ord, string))
正在使用?爲什麼有時候這是string.encode('utf-8') != 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文件。
值得注意的是,如果您確實需要通過純文本通道傳遞任意字節數據(而不是人爲地調用某個純文本通道,即使它處理任意字節),因爲OP似乎在這裏執行由於Django 1.5的限制,但我不確定...),正確的答案通常是[''surrogateescape''](https://docs.python.org/3/library/codecs.html#codec-基類) – abarnert 2014-10-06 20:14:08
@abarnert:看起來這更多的是關於瀏覽器 - Django的後處理數據傳輸。 – 2014-10-06 21:26:18
謝謝。這正是我所期待的。我不完全理解編碼,所以這很有幫助。 – 2014-10-07 01:07:09