2017-10-05 1 views
0

나는 (HTML 태그) URL에서 파일을 다운로드 할 수있는 webview 앱을 작성 중입니다. png/jpg/pdf 등의 파일을 다운로드 할 수 있지만 url은 base64 문자열 값일 때 다운로드하는 방법을 모르겠습니다. 누군가 나를 성취하도록 도와 줄 수 있습니까? 예를 들어android webview의 base64 url에서 파일 다운로드

아래의 HTML 링크 파일 을 클릭하면, 쉽게

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

을 다운로드 할 수 있습니다 abc.png 그러나 URL을 아래처럼 base64로 인 경우, 웹뷰는 "파일"을 다운로드 할 수 없습니다 : 자바 1.8를 사용하는 경우

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

@DimaKozhevin 아니, 그것은 같은 질문이 아니다. webview에 이미지를로드하고 싶지 않습니다. base64를 파일로 변환하고 장치에 저장하고 싶습니다. – Elnoor

답변

0

, 당신은

 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

+0

감사합니다.하지만 base64를 디코딩하고 비트 맵을 만든 후에 어떻게해야합니까? – Elnoor

+0

바이트 배열을 String으로 변환해야합니다. 위의 스 니펫을 수정했습니다. –

+0

에 getUrlDecoder()를 추가하여 URL 및 파일 이름 안전 디코더를 가져와야합니다. –

0

우선 당신은 다운로드를 시도보다 비트 맵 이미지 형식이 base64로 문자열을 변환해야합니다.

이와 같이 문자열을 변환 할 수 있습니다.

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


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

base64의 비트 맵을 반환합니다.

+0

좋아, 내가 비트 맵을 만든 후에, 내가 그걸로해야합니까? – Elnoor

+0

숨겨진 이미지 뷰에서이 비트 맵을 설정할 수 있습니다.이 imageview.setImageBitmap (비트 맵); 그 후 . 쉽게 다운로드 할 수 있습니다. –

+0

전에 다운로드 했으므로 죄송합니다.다른 파일의 경우에는 download과 같은 html 태그가 있으며 기본적으로 해당 파일을 클릭하면 다운로드됩니다. – Elnoor

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(); 
    } 
관련 문제