I try to send a download request to the server using ajax, and then the backend confirms that the current user has permission to download the current file and decides whether to send an error message or download the file to the browser. However, browsers can only handle error messages but cannot process download response, I have no ideal to solve this problem
This the ajax code:
<script type="text/javascript">
function fdownload(file_pk){
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
$.ajax({
url:"{% url 'file_download' %}",
type:"POST",
data:{"file_pk":file_pk},
success:function(error_message){
if(error_message == "true"){
$.Pop('you have no permission to download this file!',{Animation:'showSweetAlert'});
}
else{
.......
}
},
});
}
This is backend code:
def download_util(download_file):
file=open(download_file.file.path,'rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content- Disposition']='attachment;filename='+"".join(download_file.file.name.split('/')[-1:]).encode('utf-8').decode('ISO-8859-1')
return response
def file_download(request):
file_pk = request.POST["file_pk"]
download_file = get_object_or_404(models.Download_file,pk = file_pk)
user_group = []
file_group = []
if request.user.is_authenticated:
for e in get_object_or_404(User,username = request.user).groups.all():
user_group.append(e.name)
for e in download_file.download_permission.all():
file_group.append(e.name)
if 'anyone' in file_group or list_in(user_group,file_group):
return download_util(download_file)
else:
return HttpResponse('true')