我有一个使用JSF和PrimeFaces的Java Web应用程序。在支持bean上,我下载了本地pdf或文档文件:
public void download() throws FileNotFoundException, IOException {
File file = new File("C:/file.pdf");
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) facesContext.getExternalContext().getResponse();
response.reset();
response.setHeader("Content-Type", "application/pdf");
OutputStream responseOutputStream = response.getOutputStream();
InputStream fileInputStream = new FileInputStream(file);
byte[] bytesBuffer = new byte[2048];
int bytesRead;
while ((bytesRead = fileInputStream.read(bytesBuffer)) > 0)
{
responseOutputStream.write(bytesBuffer, 0, bytesRead);
}
responseOutputStream.flush();
fileInputStream.close();
responseOutputStream.close();
facesContext.responseComplete();
}
这就是我在xhtml上调用下载方法的方法:
<p:commandButton action="#{mybean.download()}" value="Download File" ajax="false" >
我只是通过在WebView中调用它的url为我的Java应用程序创建了一个简单的Android应用程序:
mWebView.loadUrl("http://myappurl.com");
然后我使用DownloadListener事件在WebView上监听下载:
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}
});
问题是,当我按下载按钮时,不会调用WebView的DownloadListener事件。它可以通过手机浏览器访问应用程序URL,但不能在我创建的Android应用程序中运行。
如果我将pdf放在应用程序目录中并使用简单的<a href="/file.pdf" download>
调用它,它也适用于android应用程序,但这不是我想要的,因为pdf文件将在服务器的目录中,不在申请表中。
我尝试了什么:
请帮帮我。提前谢谢。
修改
我尝试使用Chrome自定义标签取代Android WebView,效果很好,我的JSF下载得到了认可并且文件已下载,我没有做任何事情。唯一的问题是无法从Chrome自定义标签中删除工具栏,因为我希望我的应用程序看起来像是本机应用程序而不是网页。