【发布时间】:2020-07-20 18:06:55
【问题描述】:
我希望能够通过 Android 的 webview 下载文件,但我做不到。
我必须下载的网址是这种格式:
http://{server_path}/Download?mimetype=application/octet-stream
我正在使用此代码:
myWebView.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.setMimeType(mimetype);
//------------------------COOKIE!!------------------------
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
//------------------------COOKIE!!------------------------
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
long donwloadedFileId = dm.enqueue(request);
String downloadedMimeType = dm.getMimeTypeForDownloadedFile(donwloadedFileId)
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}
});
当我尝试下载时,我得到的只是一个“download.bin”文件。
当我检查函数 URLUtil.guessFileName(url, contentDisposition, mimetype) 时,它会将其作为文件名返回。
你能帮帮我吗?
编辑
如果我从 Android 文件管理器应用重命名下载的文件,它会成功打开。 所以也许答案是如何设置下载文件的正确 mimeType?
编辑 2(20 年 4 月 13 日)
另外我忘了在上面的代码中mimeType是“application/octet-stream”
【问题讨论】: