在Django中生成生成文件的下载路径

问题描述 投票:0回答:1

我有一台Django服务器,在其中生成要下载到我也在创建的Android应用程序中的文件。这些文件每个都有一个ID号,Android应用程序将具有。 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();
        }
python android django download
1个回答
0
投票

我知道了。我最终要做的是在获取歌曲的网址中添加一个整数参数:

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

然后,DownloadManager在电话上执行其操作。希望这对以后的人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.