UnicodeDecodeError with Django's request.FILES

后端 未结 4 1786
自闭症患者
自闭症患者 2021-02-09 04:28

I have the following code in the view call..

def view(request):
    body = u\"\"  
    for filename, f in request.FILES.items():
        body = body + \'Filename         


        
4条回答
  •  孤独总比滥情好
    2021-02-09 05:04

    Anurag's answer is correct. However another problem here is you can't for certain know the encoding of the files that users upload. It may be useful to loop over a tuple of the most common ones till you get the correct one:

    encodings = ('windows-xxx', 'iso-yyy', 'utf-8',)
    for e in encodings:
        try:
            data = f.read().decode(e)
            break
        except UnicodeDecodeError:
            pass
    

提交回复
热议问题