Download file using ajax and django
class downloadPredictionReport(LoginRequiredMixin,View):
def post(self,request):
logger.info("I am in downloadPredictionReport view")
pred_dir=settings.MEDIA_ROOT+'/pred_result_data/'+'predictions.csv'
if os.path.isfile(pred_dir):
with open(pred_dir, 'rb') as file:
context = file.read()
response = HttpResponse(context, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="predictions.csv"'
return response
else:
raise Http404("File does not exist")
$('#download_prediction_report_btn').click(function(e){
e.preventDefault();
var this_context = $(this);
var csrftoken = getCookie('csrftoken');
// var formData = new FormData();
console.log("I AM ON SUCCESS");
$.ajax({
url: '/download_prediction_report/',
type: 'POST',
xhrFields: {
responseType: 'blob'
},
responseType: 'arraybuffer',
headers: {
'X-CSRFToken': csrftoken
},
beforeSend: function(){
console.log("before send");
},
success: function (response) {
var csv = response;
var fileName = "prediction-report.csv";
var isMac = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true : false;
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if (!isMac) {
var BOM = "\ufeff";
csv = BOM + csv;
}
var blob = new Blob([response], {
encoding: "UTF-8",
type: "text/csv;charset=UTF-8"
});
var blobUrl = window.URL.createObjectURL(blob);
console.log(blob);
console.log(blobUrl);
//ie (naturally) does things differently
var csvLink = document.createElement('a');
if (!window.navigator.msSaveOrOpenBlob) {
csvLink.href = blobUrl;
csvLink.download = fileName;
document.body.append(csvLink);
csvLink.click();
}
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else if (isSafari) {
window.open('data:attachment/csv;charset=utf-8,' + encodeURI(csv));
}
csvLink.remove();
window.URL.revokeObjectURL(blobUrl);
},
error: function(err) {
console.log(err);
toastr.error('Sorry! No file found.')
},
complete: function(res, err){
console.log(res, err)
}
});
});
Comments
Post a Comment