我有以下问题:
我有一个WebView
.此WebView
有一个下载侦听器,当用户尝试下载文件时起作用。
我希望将文件下载到常规的"下载"文件夹。我可以通过使用
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title);
但是如何以原始名称保存文件?
我不能使用
String name = URLUtil.guessFileName(url, null, mimetype);
由于正在调用的 url 不包含文件名。
我的下载管理器目前如下所示:
mainWebView.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));
// Show a download notification
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
String title = URLUtil.guessFileName(url, null, mimetype);
// Set directory of where the file should be saved to
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title);
// Start the download
dm.enqueue(request);
}
}
注意:我目前正在使用URLUtil.guessFilename()
方法,因为这将允许我保存我的文件,如果它使用错误的名称,则为事件。
解决方案
解决方案是将正确的contentDisposition
传递给URLUtil.guessFileName()
函数。
获取标题的工作方式如下:
String title = URLUtil.guessFileName(url, contentDisposition, mimetype);
(所有参数都传递到public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength)
(