无法生成文件以使用 Django 下载

Unable to generate a file to download with Django

工作正常的部分 :

我做了一个 <form>,它的提交调用做了一个 ajax request.Code 相同的:

 $.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语句

上发现了这个错误

现在我稍微更改了解决方案,但作为响应发回的文件没有自动下载,而是打印在控制台中(因为我在 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,例如 'r'、'rb'.

如有任何帮助,我们将不胜感激!

您不能 return 向 ajax 请求发送文件并希望它被下载。你需要的是分成几个步骤:

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