Eln*_*oor 9 java base64 android download webview
我正在编写一个 webview 应用程序,我可以在其中将文件从(html 标签)url 下载到设备。我可以下载 png/jpg/pdf 等文件,但是当 url 是 base64 字符串值时,我不知道如何下载它。有人可以帮助我实现这一目标吗?
例如,当点击下面的 html 链接时,可以轻松下载文件abc.png
<a href="http://web.com/abc.png" download >Download</a>
Run Code Online (Sandbox Code Playgroud)
但是当 url 是如下 base64 时,webview 无法下载“文件”:
<a href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." download>Download</a>
Run Code Online (Sandbox Code Playgroud)
Eln*_*oor 17
我可以设法将 base64 编码的数据保存为文件。因此,对我的问题的基本简短回答是将编码数据解码为字节并将其写入这样的文件:
Run Code Online (Sandbox Code Playgroud)String base64EncodedString = encodedDataUrl.substring(encodedDataUrl.indexOf(",") + 1); byte[] decodedBytes = Base64.decode(base64EncodedString, Base64.DEFAULT); OutputStream os = new FileOutputStream(file); os.write(decodedBytes); os.close();
仅供可能提出相同问题的其他人参考,我将在下面添加我的最终代码。内部onCreate()方法我正在处理这样的文件下载:
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
if (url.startsWith("data:")) { //when url is base64 encoded data
String path = createAndSaveFileFromBase64Url(url);
return;
}
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription(getResources().getString(R.string.msg_downloading));
String filename = URLUtil.guessFileName(url, contentDisposition, mimeType);
request.setTitle(filename);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), R.string.msg_downloading, Toast.LENGTH_LONG).show();
}
});
Run Code Online (Sandbox Code Playgroud)
和createAndSaveFileFromBase64Url()方法,它涉及base64编码的数据如下所示:
public String createAndSaveFileFromBase64Url(String url) {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String filetype = url.substring(url.indexOf("/") + 1, url.indexOf(";"));
String filename = System.currentTimeMillis() + "." + filetype;
File file = new File(path, filename);
try {
if(!path.exists())
path.mkdirs();
if(!file.exists())
file.createNewFile();
String base64EncodedString = url.substring(url.indexOf(",") + 1);
byte[] decodedBytes = Base64.decode(base64EncodedString, Base64.DEFAULT);
OutputStream os = new FileOutputStream(file);
os.write(decodedBytes);
os.close();
//Tell the media scanner about the new file so that it is immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
//Set notification after download complete and add "click to view" action to that
String mimetype = url.substring(url.indexOf(":") + 1, url.indexOf("/"));
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), (mimetype + "/*"));
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(getString(R.string.msg_file_downloaded))
.setContentTitle(filename)
.setContentIntent(pIntent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
int notificationId = 85851;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notification);
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + file, e);
Toast.makeText(getApplicationContext(), R.string.error_downloading, Toast.LENGTH_LONG).show();
}
return file.toString();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8061 次 |
| 最近记录: |