django - 从django自动下载txt文件

标签 django django-views

在下面的代码中,如果我将文件输出格式更改为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"
         );

最佳答案

顺便说一句,为什么对 .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

关于django - 从django自动下载txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39346705/

相关文章:

python - Django 过滤器 LIKE 数组 ORM 中的查询(图标)

django - 名称错误 : name 'TypeError' is not defined in Apache logs

javascript - Django 管理员预填充字段不是错误 "d.Keyup is not a function"

django - 如何通过与django中某些属性的关系查询ManyToMany?

javascript - jquery ui 自动完成结果不显示在 html 下拉列表中

django - 如何限制用户使用浏览器 "back button"返回上一页(改为重定向到不同的页面)?

django - 在 Django 中使用 REST API 框架而不是简单的 URL 和 View 创建的优势?

python - 无法导入名称 HttpResponse

django - 如何激活 DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST

python - Django Python - Itertools 没有使产品与拍卖销售额保持一致