1

I trying to make an api to download file from server folder but have some problem with encoder. This is my code:

@login_required(redirect_field_name="next",login_url='login_form')
def downloadMachineLog(request):
   if(request.method == "GET"):
      fileName = request.GET.get('fileName')
      BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
      filePath = BASE_DIR+"\\reminder\\log\\"+fileName
      file_is_exists = exists(filePath)
      print(filePath)
      if(file_is_exists):
         with open(filePath,'r',encoding='utf-8-sig') as file:
            mime_type,_ = mimetypes.guess_type(filePath)
            response = HttpResponse(file,content_type = mime_type+"charset=utf-8-sig")
            response['Content-Disposition'] = "attachment; filename=%s" % fileName
         return response
      else:
         return HttpResponse("This log is not exists")
   else:
      return HttpResponse("Error")

The log file was generated using "utf-8-sig" encode. It can read fine on the server side. But if the file is downloaded from the client side the encode is wrong and shows unexpected text.

I need to download the file and be able to keep the encoder properly. what was I missing?

williamdam
  • 11
  • 1

0 Answers0