我尝试使用ajax向服务器发送下载请求,然后后端确认当前用户有权下载当前文件并决定是发送错误消息还是将文件下载到浏览器。但是,浏览器只能处理错误消息但无法处理下载响应,我没理由解决这个问题
这是ajax代码:
<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{
.......
}
},
});
}
这是后端代码:
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')