从android webview

时间:2017-10-05 06:34:15

标签: java android webview download base64

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

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

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

但是当url是base64时,webview无法下载&#34;文件&#34;:

<a href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." download>Download</a>

3 个答案:

答案 0 :(得分:0)

如果您使用的是Java 1.8,则可以尝试使用

     import java.util.Base64;

     public class DecodeBase64 {

     public static void main(String []args){
        String encodedUrl = "aHR0cHM6Ly9zdGFja292ZXJmbG93LmNvbS9xdWVzdGlvbnMvNDY1NzkyMzcvZG93bmxvYWQtZmlsZS1mcm9tLWJhc2U2NC11cmwtaW4tYW5kcm9pZC13ZWJ2aWV3LzQ2NTc5MzE0";
        byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl);
        String result = new String(decodedBytes);
        System.out.println(result);
     }
}
输出应该是:

https://stackoverflow.com/questions/46579237/download-file-from-base64-url-in-android-webview/46579314

答案 1 :(得分:0)

首先,您需要将此base64字符串转换为位图图像格式,而不是尝试下载它。

你可以像这样转换你的字符串。

public static Bitmap decodeBase64(String input)
{
    byte[] decodedByte = Base64.decode(input, Base64.DEFAULT); 


    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}

它将返回base64的位图。

答案 2 :(得分:0)

我可以设法将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();
    }
});

处理base64编码数据的createAndSaveFileFromBase64Url()方法如下所示:

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