首页 > 解决方案 > 将响应(文件)从 Django 传递到 JavaScript

问题描述

我正在努力实现以下目标:

  1. 在 Django/Python 中创建一个文件(例如带有 python-docx 模块的 Word 文档)
  2. 将响应(完整文件)传递给 JavaScript,这样我就可以用它做其他事情(例如使用 Office Javascript API)

我不确定这是否可能(我只看到了传递简单 JSON 文件的方法),但我希望得到一些帮助。我现在可以创建文件并将其下载到客户端的桌面。然后客户端必须通过其桌面来搜索文件并上传它,以便 JavaScript 可以使用它(通过 FileReader)。理想情况下,我想直接将文件发送到 Javascript,而不需要所有不必要的步骤。我的代码:

在 template.html 中:

# To download the created file from Django/Python
<input type="button" value="Download"
   onclick="window.open('filemaker/download_my_file', '_self')">

# To select the file, so Javascript can use it 
<input type='file' id='test'>

在 template.js 中:

$(document).ready(function () {
    // The document is ready
    $('#test').change(insertFile);
});

function insertFile(){
    var myFile = document.getElementById("test");
    var reader = new FileReader();

    reader.onload = function (event) {
        // some JavaScript Stuff
    };
    reader.readAsDataURL(myFile.files[0]);
}

在 urls.py 中:

urlpatterns = [
    path('/download_my_file', views.create_file_function),
]

在views.py中:

def create_file_function():
    document = Document()
    document.add_heading('Document Title', 0)

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=aass.docx'
    document.save(response)

    return response

任何想法如何从 create_file_function() 到 insertFile() 中的 var MyFile 的响应将不胜感激。非常感谢您的帮助!

标签: javascriptpythondjangohttpresponsefilereader

解决方案


推荐阅读