【问题标题】:Downloading simple text file in Django在 Django 中下载简单的文本文件
【发布时间】:2018-04-11 08:47:58
【问题描述】:

到目前为止,我正在尝试使用 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 请求时,它会在 webserver 控制台中打印以下内容,所以我认为没关系:

<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,浏览器就会自动下载文件

有什么帮助吗?

【问题讨论】:

    标签: jquery ajax django


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      浏览器不会自动对您的数据执行任何操作。您必须手动创建可下载元素并用您的数据填充它。这里还有an article how to download data with javascript

      试试看(无需使用任何库):

      $('#downloadButton').click(function(){
          $.ajax({
            url: '',
            method: 'POST',
            data: {
              request_name: 'download_txt'
            },
            success: function (data) {        
                var element = document.createElement('a');
                element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
                element.setAttribute('download', 'my-file-name');
      
                element.style.display = 'none';
                document.body.appendChild(element);
      
                element.click();
      
                document.body.removeChild(element);
            },
            error: function (err) {
              console.log('Error downloading file');
            }
          });
      });
      

      【讨论】:

      • 完美运行!这里只有一个问题:如何在 Content-Disposition 中获取我在 Django 中提供的文件名,而不是在客户端使用 JS 对其进行硬编码?
      • 嗯。我还不够聪明(还)告诉你如何在你的情况下做到这一点;)。但是您可以考虑使用JSON objects 作为您服务器的response
      【解决方案3】:

      您可以使用FileSaver 库来保存文件。操作方法如下:

      success: function (data) {
          var FileSaver = require('file-saver');
          var blob = new Blob([data], {type: "text/plain;charset=utf-8"});
          FileSaver.saveAs(blob, "filename.txt");
      },
      

      【讨论】:

        猜你喜欢
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        • 2013-04-06
        • 2013-05-25
        • 2011-01-28
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        相关资源
        最近更新 更多