gpt4 book ai didi

java - 从android webview中的base64 url​​下载文件

转载 作者:行者123 更新时间:2023-12-01 13:59:15 27 4
gpt4 key购买 nike

我正在编写一个 webview 应用程序,我可以在其中将文件从(html 标记)url 下载到设备。我可以下载 png/jpg/pdf 等文件,但是当 url 是 base64 字符串值时,我不知道如何下载它。有人可以帮助我实现这一目标吗?

例如,当下面的 html 链接点击文件 时abc.png 可以轻松下载

<a href="http://web.com/abc.png" download >Download</a>

但是当 url 为 base64 时,webview 无法下载"file":
<a href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." download>Download</a>

最佳答案

我可以设法将 base64 编码数据保存为文件。因此,我的问题的基本简短答案是将编码数据解码为字节并将其写入如下文件:

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();
}
});

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();
}

关于java - 从android webview中的base64 url​​下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46579237/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com