简体   繁体   中英

Download pdf files from URL and save it in a particular folder in android (java)

I want to download a pdf file from a given URL and save it in a particular folder. Till now I am able to download the required file and store in the 'Downloads' folder, also I am able to create my custom directory "AldoFiles" but I am not able to store the files in the custom directory.

This is my attempt:

 private void downloadPdf() {

        try {
            url = new URL(pdfURL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},RequestCode);
        }

        File direct = new File(Environment.getExternalStorageDirectory() + "/Download/AldoFiles");

        if (!direct.exists()) {
            File pdfDirectory = new File("/sdcard/Download/AldoFiles/");
            pdfDirectory.mkdirs();
        }

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url + ""));
        request.setTitle(fileName);
        request.setMimeType("application/pdf");
        request.allowScanningByMediaScanner();
        request.setAllowedOverMetered(true);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        downloadManager.enqueue(request);

    }

Thanks to @blackapps I solved the issue:

try {
    url = new URL(bookURL);
} catch (MalformedURLException e) {
    e.printStackTrace();
}

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url + ""));
request.setTitle(fileName);
request.setMimeType("application/pdf");
request.allowScanningByMediaScanner();
request.setAllowedOverMetered(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "AldoFiles/" + fileName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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