将响应(文件)从Django传递到JavaScrip

2024-04-19 13:43:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

在模板.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'>

在模板.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]);
}

在网址.py地址:

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

在视图.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

任何关于如何在insertFile()中获得create\u file\u function()到var MyFile的响应的想法都将非常感激。非常感谢你的帮助!你知道吗


Tags: 文件djangotestresponsevardownload地址type