Android Download file with Data URL


What is a Data URL?

Data URLs are the type of URL scheme that is used to embed usually small types of files. In this URL, inline files are prefixed with the data: MIME type.

data:[<mediatype>][;base64],<data>

To download files having Data URLs inside Android:

Firstly, we need to get an extension of the file from its data URL. To do the same, use following code:

Pattern pattern = Pattern.compile("(?<=data:)(.*)(?=;)");
Matcher matcher = pattern.matcher(myDataUrl);
if (matcher.find())
{
   Logger.logInfo("DECODE : "+ matcher.group(0));
   String extractedMimeType = matcher.group(0);
   extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(extractedMimeType);
   if (Util.isNullOrEmpty(extension)){
       if (extractedMimeType.contains("text/csv")){
           extension="csv";
       }else if (extractedMimeType.contains("text/plain")){
           extension="txt";
       }else if (extractedMimeType.contains("text/html")) {
           extension="html";
       }else if (extractedMimeType.contains("application/pdf")){
           extension="pdf";
       }
   }
}else {
   extension="txt";
}

Then, we need to create one file in device storage with the required extension: 

File destinationFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"download1."+extension);
  1. UrlDecoder
Example : data:Hello%20World%21

String source = URLDecoder.decode(myDataUrl).replaceAll("data:.+?,","");
BufferedOutputStream output = null;
output = new BufferedOutputStream(new FileOutputStream(destinationFile));
output.write(source.getBytes());
output.flush();
output.close();

In DataURL, the Base64 string is optional but if the URL contains Base64 encoded data, it will not be decoded and converted to a file using URLDecoder. In this case, you need to use Base64 decoding as below.

  1. Base64 decode
Example : data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==

byte[] txtAsBytes = Base64.decode(myDataUrl.split(",")[1], 0);
FileOutputStream os = new FileOutputStream(destinationFile, false);
os.write(txtAsBytes);
os.flush();
os.close();

Leave A Comment

Your email address will not be published. Required fields are marked *