在Djang中为生成的文件生成下载路径

2024-05-19 22:47:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Django服务器,我在其中生成我想要下载到我正在创建的Android应用程序的文件。这些文件中的每一个都有一个ID号,Android应用程序将拥有这个ID号。android应用程序将不知道文件的名称。我如何生成下载url,使url类似于mysite.com/download/"int id of file"/,然后我的Android应用程序将能够通过DownloadManager下载它

下面是我想用来实现这一点的代码,但欢迎对实现这一点的其他方法提出任何建议

        String url = "customurl";

        DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle("Downloading");
        request.setDescription("Downloading new titles");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "" + System.currentTimeMillis());
        request.allowScanningByMediaScanner();
        request.setAllowedOverMetered(true);
        request.setAllowedOverRoaming(true);
        long downloadReference = downloadManager.enqueue(request);
        if (downloadReference != 0) {
            Toast.makeText(getApplicationContext(), "download started", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getApplicationContext(), "no download started", Toast.LENGTH_SHORT).show();
        }

Tags: 文件idtrue应用程序urlnewrequestdownload
1条回答
网友
1楼 · 发布于 2024-05-19 22:47:12

我想出来了。我最后做的是在我为获取歌曲而创建的url中添加一个整数参数:

path('downloadsong/<int:pk>/', include('downloadsong.urls'))

从那里,我使用传入的整数从数据库中获取文件路径并返回它:

        #get mp3 file
        file_data = None
        with open(mp3Path, "rb") as f:
            file_data = f.read()

        #return file
        response = HttpResponse(file_data, content_type='audio/mpeg')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(mp3Path))
        return response

然后下载管理器在电话上完成它的工作。希望这对将来的人有所帮助

相关问题 更多 >