在 Django 中下载简单的文本文件

Rom*_*dgz 2 django ajax jquery

到目前为止,我正在尝试使用 Django 提供一个简单的文本文件,但没有成功。我认为我的 Django 代码没问题:

def status(request):
    # Get data from database
    parameters = get_parameters_from_database()
    if request.method == "GET":
        // Stuff here to render the view for a GET request
        return render_to_response('myapp/status.html', {'page_name': 'status', 'parameters' : parameters})

    elif request.method == "POST":
        if request.POST['request_name'] == 'download_txt':
            file_path = parameters['file_path']
            with open(file_path, 'rb') as fsock:
                response = HttpResponse()
                response['content_type'] = 'text/plain'
                response['Content-Disposition'] = 'attachment; filename=current.txt'
                response.write(fsock.read())
                print(response)
                return response
Run Code Online (Sandbox Code Playgroud)

当收到 POST 请求时,它会在 webserver 控制台中打印以下内容,所以我认为没关系:

<HttpResponse status_code=200, "text/html; charset=utf-8">
Run Code Online (Sandbox Code Playgroud)

所以我认为问题在于我没有在 Jquery 的 Ajax 方法中处理成功事件:

$('#downloadButton').click(function(){
    $.ajax({
      url: '',
      method: 'POST',
      data: {
        request_name: 'download_txt'
      },
      success: function (data) {        
        //TODO
      },
      error: function (err) {
        console.log('Error downloading file');
      }
    });
});
Run Code Online (Sandbox Code Playgroud)

问题是我不知道我应该如何处理成功事件:我认为浏览器会在服务器回答之后自动下载文件 content_type

有什么帮助吗?

anj*_*505 6

没有 ajax 只需返回带有文件附件的 httpresponse

from django.http import HttpResponse

def my_view(request):
   # some code
   file_data = "some text"
   response = HttpResponse(file_data, content_type='application/text charset=utf-8')
   response['Content-Disposition'] = 'attachment; filename="foo.txt"'
   return response
Run Code Online (Sandbox Code Playgroud)