Android webview 下载文件,有时候需要获取文件名,另外,有时候也需要知道扩展名。 如何获取扩展名呢,看看下面方法:
protected String mDestFileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath() + File.separator;
mWebView.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
try {
String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
if (!TextUtils.isEmpty(fileName)) {
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!MimeTypeMap.getSingleton().hasExtension(suffix)) {
suffix = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
if (!TextUtils.isEmpty(suffix)) {
fileName += "." + suffix;
}
}
downloadFile(url, fileName);
return;
}
} catch (Exception e) {
e.printStackTrace();
}
/** 或直接由系统打开
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(url));
startActivity(intent);*/
});
参考:
https://www.jianshu.com/p/6e38e1ef203a