无法使用Django生成要下载的文件

时间:2018-04-14 14:39:11

标签: python ajax django file proto

工作正常的部分

我已经提交了<form>,其提交调用发出了ajax请求。代码相同:

 $.ajax({

            type: 'POST',
            url: '/uploaded_proto_file/',
            data: formdata,
            processData: false,
            contentType: false,

            success: function (data) {
                console.log("in success")
                console.log("data is --->"+data)
                return;

            },
            error: function (data) {
                console.log("in error")

                return;
            }

        });

我可以在下面的功能中接收相同的电话。现在我需要发送一个文件(在我的文档结构中),需要在我的浏览器中自动下载。我根据这个answer

执行这个功能
def uploaded_proto_file(request):
   with open(
            '/Users/metal/Documents/test_pb2.py','rb') as text_file:
        response = HttpResponse(FileWrapper(text_file.getvalue()), content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=test_pb2.py'
        return response

上面的代码没有正常工作,所以我调试了它并在filewrapper语句中发现了这个错误

snapshot of error

现在我稍微更改了解决方案,但是响应中发回的文件没有自动下载,它在控制台中打印(因为我在ajax函数中的成功块有console.log(数据))
更改解决方案:

with open(
            '/Users/metal/Documents/test_pb2.py','rb') as text_file:
        response = HttpResponse(text_file, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=test_pb2.py'
        return response

正如您在上面所看到的,我删除了FileWrapper并且至少能够将文件发送回ajax请求。但问题仍然存在,因为文件没有自动下载。

P.S。 :我还尝试在不同的模式下打开file,例如&#39; r&#39;&#39; rb&#39;。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您无法将文件返回到ajax请求并期望将其下载。你需要的是分成几个步骤:

  • 您的ajax请求会触发文件创建过程
  • Django将该文件放在可以下载的位置,并将该URL作为ajax响应返回给该文件
  • 你的js响应处理程序现在可以做两件事:
    1. 在HTML中生成一个按钮,供用户单击并下载文件(使用响应中的URL)
    2. 创建按钮并自动单击它(在其上调用.click()),然后再次将其删除。有点像this example