2017-10-05 4 views
0

Je suis en train d'écrire une application webview dans lequel je peux télécharger des fichiers de (balise html) à l'appareil. Je peux télécharger des fichiers comme png/jpg/pdf etc, mais quand url est une valeur de chaîne base64 je ne sais pas comment le télécharger. Quelqu'un peut-il m'aider à réaliser cela?Télécharger le fichier à partir de base64 url ​​dans android webview

Par exemple, lorsque le lien html ci-dessous vous cliquez sur le fichier abc.png peut être téléchargé facilement

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

Mais quand url est base64 comme ci-dessous, WebView ne peut pas télécharger le "fichier":

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

@DimaKozhevin non, ce n'est pas même question. Je ne veux pas charger l'image sur le webview, je veux convertir base64 en fichier et l'enregistrer sur l'appareil – Elnoor

Répondre

0

Si vous utilisez Java 1.8, vous pouvez essayer avec

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

sortie doit être:

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

+0

Merci, mais que dois-je faire après avoir décodé base64 et créé un bitmap? – Elnoor

+0

vous devez convertir votre tableau d'octets en chaîne, j'ai modifié l'extrait ci-dessus –

+0

doit ajouter le getUrlDecoder() pour obtenir un URL et un nom de fichier décodeur sûr –

0

tout d'abord vous devez convertir cette chaîne base64 au format d'image bitmap que d'essayer de télécharger ce.

vous pouvez convertir votre chaîne comme ceci.

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


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

il retournera bitmap de votre base64.

+0

Ok, après avoir créé bitmap, ce que je devrais faire avec ça? – Elnoor

+0

vous pouvez définir ce bitmap dans n'importe quel imageview caché. Comme ceci imageview.setImageBitmap (bitmap); après cela. vous pouvez le télécharger facilement. comme vous avez téléchargé avant –

+0

Désolé, je n'ai toujours pas compris.Pour les autres fichiers, il y a une balise html comme: download et en gros cliquant dessus il va le télécharger – Elnoor

0

Je pourrais gérer enregistrer les données codées en base64 comme un fichier. Ainsi, la question à court de base à ma réponse a été de décoder les données codées en octets et l'écrire dans un fichier comme celui-ci:

String base64EncodedString = encodedDataUrl.substring(encodedDataUrl.indexOf(",") + 1); 
byte[] decodedBytes = Base64.decode(base64EncodedString, Base64.DEFAULT); 
OutputStream os = new FileOutputStream(file); 
os.write(decodedBytes); 
os.close(); 

Juste pour référence pour d'autres qui peut arriver à la même question que je suis en ajoutant mon code final ci-dessous. A l'intérieur méthode onCreate() je suis traitais téléchargements de fichiers comme ceci:

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

et méthode createAndSaveFileFromBase64Url() qui traite des données codées en base64 ressemble à ceci:

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