繁体   English   中英

从Android WebView中的base64网址下载文件

[英]Download file from base64 url in android webview

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

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

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

但是,当url是如下所示的base64时,webview无法下载“文件”:

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

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

如果您使用的是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

首先,您需要将此base64字符串转换为位图图像格式,然后再尝试下载该格式。

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

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


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

它将返回您的base64的位图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM