![](/img/trans.png)
[英]Selenium set preferences to download excel file but dialog box pops up?
[英]How to set up a file download dialog using Django and jQuery?
我是jQuery新手,我一直在嘗試設置文件下載對話框窗口,但未成功。 如果並且在加載對話框窗口時,用戶應該可以選擇下載動態生成的文件。 我無法設置對話框窗口。
在調試時,我可以看到生成了一個有效的http響應。 生成的內容處理數據如下:
attachment; filename=foo.csv
用例:
我的應用程序是Django Web應用程序,用於顯示Django模板上從數據庫獲取的數據。 如果用戶單擊帶有文本“導出到Csv”的按鈕,我想在需要時提供以csv格式下載顯示的數據的功能
碼
使用Javascript / HTML
/**
* Creates a file to be downloaded upon clicking a button.
*/
$('button[id*="ExportToCsv"]').click(function() {
var report_type = $(this).attr('id').split('ExportToCsv')[0];
// var report_date = '{{ report_date }}'.split('-');
$.ajax({
url: '/reports/' + report_type + '/export_to_csv/',
type: 'POST',
mimeType: 'text/csv',
data: {'report_date': '{{ report_date }}'},
success: function(data) {
return data;
}
});
});
HTML:
<button id = "ExportToCsv">Export To Csv</button>
Django的:
class CsvOutputResponse(object):
"""Handles a csv file attachment object.
Attributes:
filename: String name of the csv file.
response: HttpResponse object.
writer: Csv writer object.
"""
def __init__(self, filename):
"""Initalizes the CsvOutputResponse class.
Args:
filename: String name of the csv file.
"""
self.filename = filename
self.response = self._InitializeResponse()
self.writer = csv.writer(self.response)
def _InitializeResponse(self):
"""Initialize a csv HttpResponse object.
Returns:
HttpResponse object.
"""
response = django_dep.HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = (
'attachment; filename=%s.csv' % self.filename)
return response
def WriteRow(self, content):
"""Write a single row to the csv file.
Args:
content: List of strings of csv field values.
"""
self.writer.writerow(content)
def WriteRows(self, content):
"""Write multiple row to the csv file.
Args:
content: List of lists of strings of csv field values.
"""
self.writer.writerows(content)
def GetCsvResponse(self):
"""Get the csv HttpResponse object.
Returns:
content: HttpResponse object.
"""
return self.response
urls.py
(r'^reports/(?P<report_type>\w+)/export_to_csv/$',
'myproject.myapp.views.ExportTab')
views.py
def ExportTab(request, report_type):
"""Generates a file to be exported and made available for download.
Args:
request: HttpRequest object.
report_type: String type of report to be generated.
Returns:
HttpResponse object.
"""
report_date = request.POST['report_date']
db = database.Database()
if report_type == 'Trailing':
reports = containers.GetTrailingReports()
elif report_type == 'Ytd':
reports = containers.GetYtdReports()
return CsvOutputResponse('foo.txt').writeRows(reports).GetCsvResponse()
讓瀏覽器自然地導航到視圖,而不是在AJAX中執行POST。 然后,瀏覽器將提示您進行下載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.