【问题标题】:How to download a file from my media root folder to my phone or computer如何从我的媒体根文件夹下载文件到我的手机或电脑
【发布时间】:2021-11-13 00:10:04
【问题描述】:

每当我单击 mp3 文件或图像的下载链接时,它们并没有开始下载,而是开始在浏览器上预览。我想要当我点击 URL “http://localhost:8000/s/download_rdr/1/” 并且文件“http://localhost:8000/s/media/music.mp3” 开始下载但它所做的一切是开始在浏览器中播放。

我的意见.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')

【问题讨论】:

    标签: django


    【解决方案1】:

    尝试使用FileResponse,正如文档所说: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
    

    【讨论】:

      【解决方案2】:

      我想通了,这是完整的代码:

      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')  
      

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 2023-02-14
        • 2013-07-06
        • 1970-01-01
        • 2017-06-23
        • 2012-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多