A file name from a URL that does not contain a file name suffix

I need to download the file from the URL, except that I do not know what the file type will be, and the URL that I use does not have /random.file at the end of it, so I cannot parse the url for the name file. Right now I am using the Android download manager, which works fine and means that I am not handling the download, but I still cannot get the file name from the file loading it. If I upload the same URL in Firefox, for example, it asks for "Upload file: Nameoffile.extension".

Is there a way to reproduce this behavior and get the file name before downloading the file?

+1
source share
3 answers

I ended up using ASyncTask to manually get the file name and pass it to the download manager if it helps someone, as I did (my URL went through several redirects before the file actually downloaded):

class GetFileInfo extends AsyncTask<String, Integer, String> { protected String doInBackground(String... urls) { URL url; String filename = null; try { url = new URL(urls[0]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); conn.setInstanceFollowRedirects(false); try { for(int i = 0; i < 10; i++) { url = new URL(conn.getHeaderField("Location")); conn = (HttpURLConnection) url.openConnection(); conn.connect(); conn.setInstanceFollowRedirects(false); } } catch (Exception e) { } String depo = conn.getHeaderField("Content-Disposition"); String depoSplit[] = depo.split(";"); int size = depoSplit.length; for(int i = 0; i < size; i++) { if(depoSplit[i].startsWith("filename=")) { filename = depoSplit[i].replace("filename=", "").replace("\"", "").trim(); Global.error(filename); i = size; } } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { } return filename; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); } } 
+2
source

You better read the HTTP Content-Type header in the response and find out what type of file it is. File name extensions do not guarantee file type. Content-Disposition: attachment; filename="fname.ext" Content-Disposition: attachment; filename="fname.ext" is another way to do this if you specifically specify a file name. See the list of HTTP headers for more details.

+2
source

AsyncTask to manually download the file name:

 private static class getFileNameAsync extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { URL url; String filename = null; HttpURLConnection conn = null; try { url = new URL(params[0]); conn = (HttpURLConnection) url.openConnection(); conn.connect(); conn.setInstanceFollowRedirects(false); try { for(int i = 0; i < 100; i++) { String stringURL = conn.getHeaderField("Location"); if (stringURL != null) { url = new URL(stringURL); conn = (HttpURLConnection) url.openConnection(); conn.connect(); conn.setInstanceFollowRedirects(false); } else { i = 100; } } } catch (Exception e) { e.printStackTrace(); } String depo = conn.getHeaderField("Content-Disposition"); if (depo != null) { String depoSplit[] = depo.split(";"); int size = depoSplit.length; for(int i = 0; i < size; i++) { if(depoSplit[i].startsWith("filename=")) { filename = depoSplit[i].replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1").trim(); i = size; } } } } catch (MalformedURLException e){ e.printStackTrace(); } catch (ProtocolException e){ e.printStackTrace(); } catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } return filename; } @Override protected void onPostExecute(String filename) { super.onPostExecute(filename); } } 

DownloadListener:

  mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { if(Build.VERSION.SDK_INT >=23){ Context nContext = MainActivity.this.getApplicationContext(); if(nContext.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ MainActivity.this.requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); return; } } String fileName = ""; url = url.replace(" ", "%20"); AsyncTask<String, Void, String> asyncTask = new getFileNameAsync(); asyncTask.execute(url); try { fileName = asyncTask.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (CancellationException e) { e.printStackTrace(); } if ((fileName == null) || (fileName.hashCode() == "".hashCode())) { fileName = URLUtil.guessFileName(url, contentDisposition, mimetype); } DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setMimeType(mimetype); String cookies = CookieManager.getInstance().getCookie(url); request.addRequestHeader("Cookie", cookies); request.addRequestHeader("User-Agent", userAgent); request.setDescription("Downloading File"); request.setTitle(fileName); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); if (downloadManager != null) { downloadManager.enqueue(request); } Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show(); } }); 
0
source

All Articles