簡體   English   中英

為 Django 中生成的文件生成下載路徑

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM