[英]Android: Download file octet-stream web view
我希望能夠通過 Android 的 webview 下載文件,但我做不到。
我必須下載的 url 格式如下:
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”文件。
當我檢查 function URLUtil.guessFileName(url, contentDisposition, mimetype)
時,將其作為文件名返回。
你可以幫幫我嗎?
編輯
如果我從 Android 文件管理器應用程序重命名下載的文件,它會成功打開。 所以也許答案是如何設置下載文件的正確 mimeType?
編輯 2 (13/4/20)
另外我忘了提到在上面的代碼中 mimeType 是“application/octet-stream”
您可以嘗試對您的文件執行此操作:
File file = new File(yourFileHere);
mimeType= URLConnection.guessContentTypeFromName(file.getName());
或嘗試
Files.probeContentType(path)
編輯
將下一個 header 添加到您的請求中:
"content-disposition", "attachment; filename=\"" + fileName +"\""
@Net這里是調試output:
this = {MainActivity$1@10423}
url = "http://{server_path}/Download?mimetype=application/octet-stream"
userAgent = "Mozilla/5.0 (Linux; Android 10; Android SDK built for x86 Build/QSR1.191030.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.185 Mobile Safari/537.36"
contentDisposition = "attachment; filename*=UTF-8''M1FBACTFMB9F.pdf"
mimetype = "application/octet-stream"
contentLength = 192748
request = {DownloadManager$Request@10430}
dm = {DownloadManager@10432}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.