简体   繁体   English

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

[英]Generate download path for generated files in Django

I have a Django server in which I generate files that I want to be downloaded to an Android app I'm also creating.我有一个 Django 服务器,我在其中生成要下载到我也在创建的 Android 应用程序中的文件。 Each of these files has an ID number, which the Android app will have.这些文件中的每一个都有一个 ID 号,Android 应用程序将拥有该 ID 号。 The android app will not know the name of the files. android 应用程序不会知道文件的名称。 How can I generate download urls so that url is something like mysite.com/download/"int id of file"/ and then my Android app will be able to download it via DownloadManager?如何生成下载 url 以便 url 类似于mysite.com/download/"int id of file"/然后我的 Android 应用程序将能够通过 DownloadManager 下载它?

Below is the code that I want to use to accomplish that but any suggestions on other ways to accomplish this are welcome.下面是我想用来实现这一目标的代码,但欢迎提出有关其他实现方式的任何建议。

        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();
        }

I figured it out.我想到了。 What I ended up doing was adding an integer argument to the url I made for fetching songs:我最终做的是向我为获取歌曲而制作的网址添加一个整数参数:

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

From there, I used the integer passed in to get the file path from my database and return it:从那里,我使用传入的整数从我的数据库中获取文件路径并返回它:

        #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

And then the DownloadManager does its thing on the phone.然后 DownloadManager 在手机上做它的事情。 Hope this helps someone in the future.希望这对未来的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM