How to decode base64 string and convert it to pdf / jpg and save it in storage

I would like to decode the base64 string and turn it into a file (like pdf / jpg) and save it on the device, like in (/storage/emulated/0/Download/file.pdf).

To encode a file, I use this code:

File originalFile = new File("/mnt/sdcard/download/file.pdf"); String encodedBase64 = null; try { FileInputStream fileInputStreamReader = new FileInputStream(originalFile); byte[] bytes = new byte[(int) originalFile.length()]; fileInputStreamReader.read(bytes); encodedBase64=Base64.encodeToString(bytes,Base64.NO_WRAP); messaggio=encodedBase64.toString(); //encodedBase64 = new String(Base64.encode(bytes)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

Now I would like to deactivate this base64 string and convert it to a file and save it on the device ...

Can someone help me?

Thanks to everyone =)

+5
source share
1 answer

You can try the following:

 FileOutputStream fos = new FileOutputStream(filepath); fos.write(Base64.decode(base64String, Base64.NO_WRAP)); fos.close(); 

Where:

  • filepath: Path to the new file
  • base64String: The base64 string you want to convert
+11
source

Source: https://habr.com/ru/post/1246966/


All Articles