简体   繁体   中英

Android - Open PDF from URL with filename set via HTTP headers by Intent

I wrote a small android app that features a link to a PDF file on the web. The problem is, that the link is a generic link without a proper file suffix. The webserver serving the file will however send a real filename with a proper suffix and force the webbrowser to save the file under a nice name (very common practice for file downloads). This works fine on any desktop browser like FF or IE, but if I start a VIEW Intent on my Android, it starts a download under the original file, resulting in a file that has no suffix and is not associated with any program.

(Adobe Reader is installed and a manually renamed download opens just fine)

Example: A link to " http://mysample.com/file/6dbfj73bdngdn3 " will be changed by headers to "mysamplefile.pdf"

Here is the PHP snippet on the server, setting the headers for the downloaded file:

header("Expires: 0");
header("Pragma: public");
header("Cache-Control: private, must-revalidate, post-check=0, pre-check=0");
header("Content-length: 12345");
header("Content-type: application/force-download; filename=\"mysamplefile.pdf\"");
header("Content-type: application/octet-stream; filename=\"mysamplefile.pdf\"");
header("Content-type: application/download; filename=\"mysamplefile.pdf\"");

I tried several methods to open the intend, this is my current one. If I specify a mime type, I get an ActivityNotFoundException, if I dont, I get the above mentioned download under original filename without a suffix.

String url = "http://mysample.com/file/6dbfj73bdngdn3";
//Intent i = new Intent(Intent.ACTION_VIEW);
//i.setDataAndType(Uri.parse(url), "application/pdf");
Intent i = new Intent(Intent.ACTION_VIEW, URI.parse(url));

I ended up with opening the URL in the Webbrowser via it's Intent. The problem is that this browser is exceptionally picky with the headers you send. if you have blanks in your Content-Type headers between each element, Android will ignore them.

Wrong:

header("Content-type: application/download; filename=\"mysamplefile.pdf\";");

Correct:

header("Content-type: application/download;filename=\"mysamplefile.pdf\"");
String url = "http://mysample.com/file/6dbfj73bdngdn3";
WebView mWebView=new WebView(MyPdfViewActivity.this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+url );
setContentView(mWebView);

this will open the pdf in a webview inside google docs -- Linkto is the url to your pdf file

i am not sure if this is what you want hope ll help in some way

but your url is retuning an error doc dsnt exists

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