简体   繁体   中英

While downloading xls file from django download code, file is not opening, It shows corrupted

Here is my code for xls download using python(Django)

views.py

def downloadfile(request, filename=''):
  if filename != '':
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    filename = 'SampleExcel.xls'
    filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls"
    path = open(filepath, encoding='cp437')
    mime_type, _ = mimetypes.guess_type(filepath)
    response = HttpResponse(path, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    return response
  else:
    return HttpResponseRedirect("adduser", {})

With this code I am able to download file properly, but while opening that file it shows me error. I attach screenshot of error.

在此处输入图像描述

I have tried this code for solution,

if filename != '':
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  filename = 'SampleExcel.xls'
  filepath = BASE_DIR + "\SampleExcel\SampleExcel.xls" 
  return FileResponse(open(filepath, 'rb') , True, filename)
else:
  return HttpResponseRedirect("adduser", {})

This also not works, It shows error 'TypeError at /downloadfile/SampleExcel.xls HTTP status code must be an integer.', and it is not even downloading.

Please help me. I am stuck here from last 3 days.

Note: I need to download xls file only, as after downloading it I have to perform import functionality with that downloaded xls file. I can not change xls to xlsx.

Error Log

Traceback (most recent call last): File "C:\Users\PCSI\AppData\Local\Programs\Python\Python310\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\PCSI\AppData\Local\Programs\Python\Python310\lib\wsgiref\handlers.py", line 184, in finish_response self.write(data) File "C:\Users\PCSI\AppData\Local\Programs\Python\Python310\lib\wsgiref\handlers.py", line 279, in write assert type(data) is bytes, \ AssertionError: write() argument must be a bytes instance [27/Jun/2022 15:07:10] "GET /downloadfile/SampleExcel.xls HTTP/1.1" 500 59

The FileResponse one will work, the issue is that you are not setting the proper keyword arguments.

path = open(filepath, 'rb')
response = FileResponse(path, as_attachment=True, filename=filename)

Make sure you have added the 'rb' to the open and this should work for you.

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