【问题标题】:download txt file automatically from django从 django 自动下载 txt 文件
【发布时间】:2017-01-13 18:36:43
【问题描述】:

在下面的代码中,如果我将文件输出格式更改为 output.csv,文件将自动下载,但如果我将格式更改为 output.txt,文件将显示在浏览器上。如何自动下载输出。 txt文件

由于 csv 文件被下载,相同代码的 txt 文件有什么问题

   def downloadcsv(request):
        try:
            response = {}
            output = fq_name+"/"+ "output.txt"
            os.system(cmd)
            logger.debug(file_name)
            response.update({'status':0,'message': 'Success','file_name' : output})
        except Exception as e:
            response['message'] = "Exception while processing request"
            response['status'] = 2
            logger.exception(e)
        return HttpResponse(JsonResponse(response), content_type="application/json")

$.post("/reports/downloadcsv/", snddata,
        function callbackHandler(data, textstatus)
        {
            if (data.status == 0)
            {
                document.location.href = data.file_name;
                 //document.getElementById('my_iframe').src = data.file_name;
            }
            else if (data.status == 1 || data.status == 2)
            {
                $('#loading').hide();
                alert('Error while processing data');
            }
            $('#loading').hide();
         },
         "json"
         );

【问题讨论】:

  • Django download a file的可能重复
  • 重复:您需要发送 Content-Disposition 标头
  • 即使我不发送 csv 文件的 Content-Disposition 标头,它也会被下载,现在 txt 文件有何不同

标签: django django-views


【解决方案1】:

顺便说一句,您为什么对 .txt 文件使用“application/json”而不是 .json?

很难可靠地控制不同浏览器在服务器端对特定文件或内容类型执行的操作,因为浏览器会根据用户的偏好进行操作:在浏览器中打开、打开另存为对话框、在第 3 方程序中打开、用插件等处理。

你可以试试HTML5下载属性:http://www.w3schools.com/TAgs/att_a_download.asp

这里提出的其他解决方案:Force to open "Save As..." popup open at text link click for pdf in HTML

【讨论】:

    【解决方案2】:

    您正试图返回一个 .txt,但它被设置为返回 .json

    改变

    return HttpResponse(JsonResponse(response), content_type="application/json")
    

    到:

    return HttpResponse(JsonResponse(response), content_type="application/default")
    

    我已尝试使用此代码并且它有效:

    from django.conf import settings
    from django.http import HttpResponse, Http404
    
    def download(self, request, path):
            file_path = os.path.join(settings.MEDIA_ROOT, path)
            if os.path.exists(file_path):
                with open(file_path, 'rb') as fh:
                    response = HttpResponse(fh.read(), content_type="application/default")
                    response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
                    return response
            raise Http404
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2016-10-24
      • 2020-07-29
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 2016-02-14
      • 2019-02-27
      • 1970-01-01
      相关资源
      最近更新 更多