【问题标题】:Python Django- How to download file on client machine in django projectPython Django-如何在 Django 项目中的客户端计算机上下载文件
【发布时间】:2020-03-09 13:22:22
【问题描述】:

我是 python 新手, 我创建了一个小型 Django 应用程序来将数据下载为 excel 格式。 它下载到项目文件夹或给定路径(在服务器上)。

但是当我从客户端机器上点击 URL 时,它应该在客户端机器上下载,但它只下载到我的服务器上。 请建议一个合适的方法(代码)仅在客户端机器上下载一个 excel 文件。

提前致谢。

-------代码-------

try:
    cursor = connection.cursor()
    cursor.execute("""select * from table""")

    columns = [desc[0] for desc in cursor.description]
    data = cursor.fetchall()
    result = len(data)
    print("No of records :" ,len(data))
    df = pd.DataFrame(list(data), columns=columns)

    home = os.path.expanduser("~")
    print('Home path------------',home)
    download_location = os.path.join(home,'Downloads')
    print('download path------------',download_location)

    filename = 'django_simple.xlsx'

    writer = pd.ExcelWriter(download_location+'/'+ filename)
    df.to_excel(writer, sheet_name='Hundai')
    writer.save()

    print("File saved successfully!")
    cursor.close()
except:
    print("There is an error")    
finally:
    if (connection):
        connection.close()
        cursor.close()
        print("The MSSQL connection is closed")   

return render(request,'result.html',{'result': result})

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    看看这个非常简单但有效的代码。

    import pathlib
    from django.http import FileResponse
    
    def download(request):
        file_server = pathlib.Path('the_path_of_your_file_to_download')
        if not file_server.exists():
            messages.error(request, 'file not found.')
        else:
            file_to_download = open(str(file_server), 'rb')
            response = FileResponse(file_to_download, content_type='application/force-download')
            response['Content-Disposition'] = 'inline; filename="a_name_to_file_client_hint"'
            return response
        return redirect('a_url_path')
    

    【讨论】:

      【解决方案2】:
      from django.http import HttpResponse
      
      
      try:
          cursor = connection.cursor()
          cursor.execute("""select * from table""")
      
          columns = [desc[0] for desc in cursor.description]
          data = cursor.fetchall()
          result = len(data)
          print("No of records :" ,len(data))
          df = pd.DataFrame(list(data), columns=columns)
      
          home = os.path.expanduser("~")
          print('Home path------------',home)
          download_location = os.path.join(home,'Downloads')
          print('download path------------',download_location)
      
          filename = 'django_simple.xlsx'
      
          writer = pd.ExcelWriter(download_location+'/'+ filename)
          df.to_excel(writer, sheet_name='Hundai')
          writer.save()
      
          print("File saved successfully!")
          cursor.close()
      
          with open(download_location+'/'+ filename, 'rb') as fh:
              response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
              response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
              return response
      
      except:
          print("There is an error")    
      finally:
          if (connection):
              connection.close()
              cursor.close()
              print("The MSSQL connection is closed")   
      
      return render(request,'result.html',{'result': result})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-28
        • 1970-01-01
        • 2018-03-12
        • 2017-03-15
        • 1970-01-01
        • 2015-07-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多