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

标签 jquery ajax django

到目前为止,我正在尝试使用 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

当收到 POST 请求时,它会在网络服务器控制台中打印以下内容,所以我认为没问题:

<HttpResponse status_code=200, "text/html; charset=utf-8">

所以我认为问题是我没有在 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');
      }
    });
});

问题是我不知道应该如何处理成功事件:我认为一旦服务器用 content_type 应答,浏览器就会自动下载文件

有什么帮助吗?

最佳答案

没有 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

关于jquery - 在 Django 中下载简单的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49770572/

相关文章:

java - Struts ajax 404错误

php - 使用 PHP 和 AJAX 插入 MySQL 记录

javascript - 如何使用 Javascript 轻松监听 xhr 请求?

python - Django REST 框架 (DRF) : TypeError: register() got an unexpected keyword argument 'base_name'

python - ElasticSearch/Solr-产品站点的同义词?

python - 两个日期之间的 Django ORM 交集

javascript - 如何获取包含特定子项的元素的索引

javascript将子字符串替换为重复次数的值

javascript - 如何获取鼠标输入的元素ID?

javascript 使用复选框迭代对象数组