javascript - 将响应(文件)从 Django 传递到 JavaScript
问题描述
我正在努力实现以下目标:
- 在 Django/Python 中创建一个文件(例如带有 python-docx 模块的 Word 文档)
- 将响应(完整文件)传递给 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 的响应将不胜感激。非常感谢您的帮助!
解决方案
推荐阅读
- python - 从 GCS 读取输入和架构作为运行时参数的数据流模板
- javascript - 为什么 requestAnimationFrame() 嵌套在这个 if 语句中时不起作用?
- java - 不推荐使用 environment.getexternalstoragedirectory() 后如何访问外部存储
- c++ - 返回指向结构的指针,如何自动释放内存?
- javascript - 希望修改 Javascript 按钮颜色
- c# - 我在 datagridview 中选择了一列作为数组,如何显示选定的数组值?
- c++ - 访问器函数可以调用纯虚函数吗?
- c - 链接和使用头文件有什么区别?
- java - 数据库保存后是否真的有必要从事务中返回保存的实体?
- c# - HTML 电子邮件正文 Base64 图像未显示