[英]How do I encode/decode a file correctly after reading it through javascript and pass the file data through ajax?
我有一個django File字段,其中多個屬性設置為true。 我試圖做一個多文件上傳器,在這里我用一個簡單的javascript FileReader對象獲得文件對象。 遍歷文件列表后,我通過讀取文件數據
reader.readAsBinaryString(file);
並獲得所需的文件數據結果。 通過ajax將這些數據傳遞到我的視圖后,我試圖將文件的副本創建到media文件夾中。 我目前正在使用以下視圖功能:
@csrf_exempt
def storeAttachment(data):
'''
stores the files in media folder
'''
data = simplejson.loads(data.raw_post_data)
user_org = data['user_org']
fileName = data['fileName']
fileData = data['fileData']
file_path = MEDIA_ROOT + 'icts_attachments/'
try:
path = open((file_path+ str(user_org) + "_" + '%s')%fileName, "w+")
path.write(fileData)
path.close()
return HttpResponse(1)
except IOError:
return HttpResponse(2)
我能夠編寫簡單的文本文件,.js,.html和其他幾種格式,但是當我嘗試上載pdf,word,excel,rar格式時,即使保存了無效數據文件,我在響應中也遇到以下錯誤我的媒體路徑(該文件無法打開)。
'ascii' codec can't encode characters in position 41-42: ordinal not in range(128)
我嘗試使用各種引用對文件數據進行編碼/解碼,但沒有效果。任何建議將不勝感激。
由於使用Python 2
的默認ASCII編碼,因此出現錯誤。 大於127的字符會導致異常,因此請使用str.encode
將Unicode編碼為文本/字節。
優良作法是在處理文件對象時with
關鍵字一起使用。
path = u''.join((file_path, user_org, '_', fileName)).encode('utf-8')
with open(path, 'w+') as f:
f.write(fileData)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.