[英]Generate download path for generated files in Django
我有一个 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();
}
我想到了。 我最终做的是向我为获取歌曲而制作的网址添加一个整数参数:
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 在手机上做它的事情。 希望这对未来的人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.