首页 > 解决方案 > 如何将文件从 Django 后端发送到服务器

问题描述

我正在向处理它的后端发送带有文件的 ajax 请求。在将其处理成另一种形式(图像到压缩的处理目录)后,我想将其发送回用户以下载它。有人可以提供一个示例视图,该视图将在收到文件时处理数据并发送具有该文件的请求。另外,请告诉我如何在 javascript 前端下载该文件。

class send_text:
    def post(self, request):
        file = request.POST["file"]
        # Processing…………… file_to_send = <path to file>
        # show how to send the file here

还有前端:

$.ajax{
//sending the data
onSuccess: //show how to download the data here
}

先感谢您。

标签: javascriptpythonhtmldjango

解决方案


对于其他任何人,我已经通过使用静态文件来解决这个问题。请使用带有下载选项的标签。例如:

<a href="{%get_static_prefix%}{{file_name}}/{{file_name}}.pdf" id="printer" download='{{file_name}}.pdf'></a>

请注意,如果您想为用户自动下载文件,请创建一个函数。在函数里面输入这个:

document.getElementById("<<name of <a> tag, here: printer>>").click()


推荐阅读