![](/img/trans.png)
[英]Heroku App, Created File with Python, how can I get the download url?
[英]How can I download a word document created by a django app on the same app
我有一個django
應用程序,它可以從模板創建一個 word 文檔。 用戶輸入后,我向我的views.py
發出ajax
請求並創建文檔。 創建文檔后,我希望從服務器下載它。 文檔保存在 static/documents 文件夾中。 在我的模板中,我有以下內容:
$.ajax({
url: '/ajax/result/',
data : { 'values': JSON.stringify(dataJson),
'general': JSON.stringify(generalData)
},
method: 'GET',
contentType: "application/json",
dataType: 'json',
success: function (data){
Download('documents/'+document.getElementById('id_file_name').value+'.docx');
alert(data);
},
error: function(data) {
alert("something went wrong");
}
});
function Download(url) {
document.getElementById('my_iframe').src = url;
};
Download(url)
function是下載文件的function。 我可以獲取文檔的文件名,因為它來自用戶輸入。 我目前在控制台上收到 404 錯誤。 提前致謝
您需要聲明實際文件路徑
Download('http://127.0.0.1:8000/something/something/documents/'+document.getElementById('id_file_name').value+'.docx');
如果您可以將此技術用於您的意見:
file_name = ## your file name
file_root = ## your file root
with open(file_root , 'rb') as f:
wrapper = FileWrapper(f)
mimetype = "application/force-download"
guessed_type = guess_type(file_name)[0]
if guessed_type:
mimetype = guessed_type
response = HttpResponse(wrapper, mimetype)
response['Content-Disposition'] = "attachment;filename=%s"%(download_obj.get_name)
response['X-SendFile'] = "%s"%(download_obj.get_name)
return response
不要忘記在您的 views.py 文件的頂部導入必要的東西:
from django.shortcuts import HttpResponse
from mimetypes import guess_type
from wsgiref.util import FileWrapper
為此視圖創建一個新的 url,並從 ajax 中點擊 url,您可以將文件名動態傳遞給視圖
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.