简体   繁体   中英

'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte django

so i have variable contains with bytes and i want to write it to text and download it. but to use write, it's must in bytes. so how to make from bytes to string?

now i got error like this. i tried to decode it, but it cannot works.

'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte

here's the code:

def create_file(f):
    print(f) #f = b'\x8b\x86pJ'
    response = HttpResponse(content_type="text/plain")
    response['Content-Disposition'] = 'attachment; filename=file.txt'

    filename = f
    print(filename) # filename = b'\x8b\x86pJ'
    download = filename.decode('utf-8')
    response.write(download)
    print(response)

    return response

You can try

def create_file(f):
    print(f) #f = b'\x8b\x86pJ'
    response = HttpResponse(content_type="text/plain")
    response['Content-Disposition'] = 'attachment; filename=file.txt'

    filename = f
    print(filename) # filename = b'\x8b\x86pJ'
    download = filename.decode('latin-1')
    response.write(download)
    print(response)

    return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM