业务需求,页面点击后将后端的queryset写入文件返回给前端下载
前端代码js是抄的,找不到出处了
$http.get("url", { responseType: "arraybuffer" })
.success( function(data, status, headers) {
var success = false;
// Get the headers
headers = headers();
// Get the filename from the x-filename header or default to "eventlog"
var filename = headers['x-filename'] || 'eventlog.csv';
// Determine the content type from the header or default to "application/octet-stream"
var contentType = headers['content-type'];
// Get the blob url creator
var urlCreator = window.URL || window.webkitURL;
if(urlCreator)
{
// Try to use a download link
var link = document.createElement('a');
if('download' in link)
{
// Try to simulate a click
try
{
// Prepare a blob URL
console.log("Trying download link method with simulated click ...");
var blob = new Blob([data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
link.setAttribute('href', url);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
console.log("Download link method with simulated click succeeded");
success = true;
} catch(ex) {
console.log("Download link method with simulated click failed with the following exception:");
console.log(ex);
}
}
//此处省略其他情况代码(我没用到)
}
})
.error(function(data, status) {
var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
var obj = JSON.parse(decodedString);
var message = obj['message'];
toastr.error(message);
// Optionally write the error out to scope
$scope.errorDetails = "Request failed with status: " + status;
});
后端代码(python2):
response = HttpResponse(content_type='text/csv') # 告诉浏览器是text/csv格式
writer = csv.writer(response)
field_list = [ 'user']
writer.writerow(field_list)
for data in queryset:
writer.writerow([data.user])
return response