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).