如何从我的媒体根文件夹下载文件到我的手机或电脑



每当我点击mp3文件或图像的下载链接,而不是他们开始下载,但他们只是开始预览在浏览器上。我想当我点击url "http://localhost:8000/s/download_rdr/1/"文件"http://localhost:8000/s/media/music.mp3"开始下载,但它所做的只是在浏览器中开始播放。

我views.py

class DownloadRdr(TemplateView):

def get(self, request, pk, *args, **kwargs):

item = Item.objects.get(id=pk) 

#Return an mp3
return redirect('http://localhost:8000/s/media/music.mp3')

我明白了,这里是一个完整的代码:

class DownloadRdr(TemplateView):

def get(self, request, pk, *args, **kwargs):
if request.user.is_authenticated:
item = Item.objects.get(id=pk) 
#order data check
orderDataCheck = OrderData.objects.filter(item=item, user=request.user)
orderDataCheck_count = orderDataCheck.count()
if orderDataCheck_count > 0:
#Return an mp3
image_buffer = open(item.upload_file.path, "rb").read()
response = HttpResponse(image_buffer)
response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(item.upload_file.path)
return response

#return redirect(item.upload_file.url)
else :
return HttpResponse('<h4>Error, You do not have access to this product!</h4>')
else:
return redirect('accounts:login_page')  

尝试使用FileResponse作为docs所说的:https://docs.djangoproject.com/en/3.2/ref/request-response/#fileresponse-objects

from django.http import FileResponse
def get(self, request, pk, *args, **kwargs):
...
response = FileResponse(open(YOUR_FILE_PATH, 'rb'), as_attachment=True)
return response

相关内容

最新更新