I'm trying to download the file from the server using DownloadManager but It fail's to download and say's Download unsuccessful, I have read that there is a issue with Download Manager in the below link
android-chrome-browser-unnecessarily-renames-names-types-of-downloaded-files so I tried to download the file by adding the RequestHeader to the DownloadManagerRequest using below method but nothing happened. please find the below code part of my Downloader class anyone please suggest me the right way to download the file from url using DownloadManager.
url:
http://-storage..net/95-****/95-3194.pdf?AWSAccessKeyId=T9YG9HWQC1LHE5G5VF38&Expires=1483443248&Signature=Z%2BkWzfEI2VawbCx%2F2Yto1kPcJKA%3D
Thanks
public void download(Uri uri) {
if (!isDownloading()) {
String fileName=getName(uri);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setNotificationVisibility(1);
request.allowScanningByMediaScanner();
request.addRequestHeader("Content-Type", "application/octet-stream");
request.addRequestHeader("Content-Disposition", "attachment; filename=\""+fileName.split("\\.")[0]+"."+fileName.split("\\.")[1].toUpperCase()+"\"");
String cookieContent = getCookieFromAppCookieManager(uri.getHost());
request.addRequestHeader("Cookie", cookieContent);
downloadId = downloadManager.enqueue(request);
register();
}
}
and below block returns the File name
private String getName(Uri uri) {
String name=uri.toString().split("jabord/")[1].split("\\?")[0];
return name;
}
returns the appcookie manager
public String getCookieFromAppCookieManager(String url) {
android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
if (cookieManager == null) {
return null;
}
String rawCookieHeader = null;
// Extract Set-Cookie header value from Android app CookieManager for this URL
rawCookieHeader = cookieManager.getCookie(url);
if (rawCookieHeader == null) {
return null;
}
return rawCookieHeader;
};
Please remove the headers and set the mimetype and then it will work. For example
public void download(Uri uri) {
if (!isDownloading()) {
String fileName=getName(uri);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setNotificationVisibility(1);
request.allowScanningByMediaScanner();
request.setMimeType("application/pdf");
Log.e("Extension with ","UpperCase-->"+"\""+fileName.split("\\.")[0]+"."+fileName.split("\\.")[1].toUpperCase()+"\"");
downloadId = downloadManager.enqueue(request);
register();
}
}
I was also facing the same issue. I solved it by removing the cookies.
Related
I am trying to download files inside my Webview. I use DownloladListener to handle download request and then I use DownloadManager to download file. Everything works well but I can't get name and extension of file from url's like this one: http://unionpeer.com/dl.php?t=1502119 (This is assassins creed movie .torrent file). How can I get at least file extension? Thanks in advance!
Downloading the file:
String url = (String) objects[0];
String defaultDownloadPath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true).setTitle(getFileName(url))
.setDescription("Download")
.setDestinationInExternalPublicDir(getPublicExternalPath(defaultDownloadPath),
getFileName(url));
dm.enqueue(request);
getfileName() - works a little better than URLUtils.guessFileNameFromUrl()
String temp = "";
String extension = url.substring(url.lastIndexOf("."));
for (int i = 0; i < extension.length(); i++) {
if (i != 0){
if (!Character.isLetter(extension.charAt(i)) && !Character.isDigit(extension.charAt(i))) {
break;
}
}
temp += extension.charAt(i);
}
return String.valueOf(System.currentTimeMillis() + temp);
I am trying to download files using dropbox url. I copied a code from Download a file with Android, and showing the progress in a ProgressDialog which uses DownloadManager class.
public void downloadFromDropBoxUrl(View view) {
//verfying if the downloadmanager is available first.
if (isDownloadManagerAvailable(getApplication())) {
String url = "https://www.dropbox.com/s/m4z5u9qstxdtbc3/AllExams22.pdf?dl=0";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my-map.pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
}
public static boolean isDownloadManagerAvailable(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
return true;
}
return false;
}
It is working on achiving direct files with urls but this time I am trying to do it with dropbox share links but its not working out. I don't want to connect to dropbox api. I think it is useless. Is there any way I can download files directly from the dropbox url?
just replace
String url = "https://www.dropbox.com/s/m4z5u9qstxdtbc3/AllExams22.pdf?dl=0";
by:
String url = "https://dl.dropboxusercontent.com/s/m4z5u9qstxdtbc3/AllExams22.pdf";
Then:
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute(url);
Please see this link on how to download a shared file from Dropbox
https://blogs.dropbox.com/developers/2013/08/programmatically-download-content-from-share-links/
I'm trying to make a method to download a file, but inside the method in the request, it has a call to a function that show a notification of the download. The problem is that the minimum api required for my app is API 9, and the IDE shows me an error because setNotificationVisibility is for API 11 and above.
This is my source code:
public void init_download(String title, String filename, String url) {
File path = new File(Environment.DIRECTORY_DOWNLOADS);
if (!path.exists()) {
path.mkdirs();
}
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(title)
.setDescription(getResources().getString(R.string.downloading))
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
long id = downloadManager.enqueue(request);
//Save the request id
SharedPreferences.Editor PrefEdit = shared_pref.edit();
PrefEdit.putLong("DOWNLOAD_ID", id);
PrefEdit.commit();
}
How can I solve this to run notifications in both versions?
Thank you.
Add #SuppressLint("NewApi") to the declaration of your functioin, this is:
#SuppressLint("NewApi")
public void init_download(String title, String filename, String url) {
}
You can solve the warning with #SuppressLint("NewApi")but in lower API's your setNotificationVisibility will not work as there is no DownloadManager in support packages.
I've solved the last problem by changing the VISIBILITY of the notification:
public void init_download(String title, String filename, String url) {
File path = new File(Environment.DIRECTORY_DOWNLOADS);
if (!path.exists()) {
path.mkdirs();
}
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(title)
.setDescription(getResources().getString(R.string.downloading))
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
else {
request.setShowRunningNotification(true);
}
long id = downloadManager.enqueue(request);
//Save the request id
SharedPreferences.Editor PrefEdit = shared_pref.edit();
PrefEdit.putLong("DOWNLOAD_ID", id);
PrefEdit.commit();
}
This is to download a file to the Downloads directory of your android device.
You should add #SuppressLint("NewApi") before your method. But it will be better to up min sdk version or don't use this method. If you add #SuppressLint("NewApi") don't forget about users that can run you app on device with 9 api.
i have created a webview app i added downloader inside which download the file end with m4a..the app downloads the file but file name changes...how can get title from the file...
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle different requests for different type of files
// this example handles downloads requests for .m4a and .mp3 files
// everything else the webview can handle normally
if (url.endsWith(".m4a")) {
Uri source = Uri.parse(url);
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
request.setTitle(getTitle());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "filename");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else if(url.endsWith(".mp3")) {
// if the link points to an .mp3 resource do something else
}
// if there is a link to anything else than .m4a or .mp3 load the URL in the webview
else view.loadUrl(url);
return true;
}
});
This will give you your file name
final String[] separated = url.split("/");
final String myFile = separated[separated.length - 1];
It will split the url using the / character and you take the last element in the returned array.
Arrays are 0 based, so the last element is the one located at the vector's length - 1.
Put the above code just before this line: if (url.endsWith(".m4a")) {, where you want to get your file name.
Then, use it so:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, myFile);
Full code for downloading file inside webview without calling web-browser
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle different requests for different type of files
// this example handles downloads requests for .m4a and .mp3 files
// everything else the webview can handle normally
if (url.endsWith(".m4a"))
{
Uri source = Uri.parse(url);
final String[] separated = url.split("/");
final String myFile = separated[separated.length - 1];
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, myFile);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else if (url.endsWith(".pdf"))
{
Uri source = Uri.parse(url);
final String[] separated = url.split("/");
final String myFile = separated[separated.length - 1];
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, myFile);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
// if there is a link to anything else than .m4a or .mp3 load the URL in the webview
else view.loadUrl(url);
return true;
}
});
I am trying to perform a direct download inside the WebView, not linking to the browser.
webview.setDownloadListener(new DownloadListener() {
#SuppressLint("DefaultLocale")
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
MimeTypeMap mtm = MimeTypeMap.getSingleton();
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(url);
// get file name. if filename exists in contentDisposition, use it. otherwise, use the last part of the url.
String fileName = downloadUri.getLastPathSegment();
int pos = 0;
if ((pos = contentDisposition.toLowerCase().lastIndexOf("filename=")) >= 0) {
fileName = contentDisposition.substring(pos + 9);
pos = fileName.lastIndexOf(";");
if (pos > 0) {
fileName = fileName.substring(0, pos - 1);
}
}
// predict MIME Type
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
String mimeType = mtm.getMimeTypeFromExtension(fileExtension);
// request saving in Download directory
Request request = new DownloadManager.Request(downloadUri);
request.setTitle(fileName);
request.setDescription(url);
request.setMimeType(mimeType);
request.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, fileName);
Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).mkdirs();
// request in download manager
downloadManager.enqueue(request);
}
});
And to open it,
// download complete toast
private BroadcastReceiver completeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Resources res = context.getResources();
// make toast
Toast.makeText(context, res.getString(R.string.download_complete), Toast.LENGTH_SHORT).show();
// go to download finished window
startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
}
};
#Override
protected void onPause() {
super.onPause();
// if app stops, stop reciever
unregisterReceiver(completeReceiver);
}
#Override
protected void onResume() {
// app start, start reciever
IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(completeReceiver, completeFilter);
super.onResume();
}
}
However, the result is not the original file, but the HTML format of the source using the original file extension; e.g. it uses .pdf, but is a HTML file.
What is causing this problem, and How can I fix it?
Files I get
First of all, it is impossible to open with a normal PDF viewer, and when I don't open it as PDF, I get a normal HTML document:
<!DOCTYPE html>
<html>
…
</html>
There is NOTHING SPECIAL in the HTML document.
I found that your filename is coming with quote so just replace it.
fileName=fileName.replaceAll("\"", "");
you will get the proper file. I have also used that code in mine and it's successfully worked.