0

In my application, many users can upload files. There is no fixed file type as the user can upload any kind of file. I am trying to create a view through which the file could be downloaded.

It goes like this

def download_file(request,id):
    file = t_data.objects.get(id=id)
    fl_path = "media/file_name.extension"
    filename = file.file_name
    fl = open(fl_path, 'r')
    mime_type, _ = mimetypes.guess_type(fl_path)
    response = HttpResponse(fl, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    return response

I am able to download .txt files but files with other extensions aren't downloading. Instead, I get this error when i try to download .py file

UnicodeDecodeError at /download/9 'charmap' codec can't decode byte 0x9d in position 375: character maps to Request Method: GET Request URL: http://127.0.0.1:8000/download/9 Django Version: 3.1.7 Exception Type: UnicodeDecodeError Exception Value:
'charmap' codec can't decode byte 0x9d in position 375: character maps to Exception Location: C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py, line 23, in decode Python Executable: C:\Users\ukfle\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path:
['C:\Users\ukfle\Documents\pro', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39', 'C:\Users\ukfle\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypal_checkout_serversdk-1.0.0-py3.9.egg', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\win32', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\win32\lib', 'C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\Pythonwin'] Server time: Thu, 27 May 2021 11:41:34 +0000

I am quite beginner and don't know whats the problem. Please help me solve it. Thank you.

If there is another approach for downloading files of all types, Please share those too(or links of documentation).

Utsavkaf
  • 21
  • 6
  • try this ```open(fl_path, 'r', encoding="utf8")``` – Sumithran May 27 '21 at 11:51
  • Does this answer your question? [UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to ](https://stackoverflow.com/questions/9233027/unicodedecodeerror-charmap-codec-cant-decode-byte-x-in-position-y-character) – Sumithran May 27 '21 at 11:52
  • Thanks, It worked for text related files, But It didn't for images and others. If you have any solutions for those also, please..@Sumithran – Utsavkaf May 28 '21 at 05:57

0 Answers0