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

混江龙づ霸主 提交于 2019-12-01 15:10:10

问题


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

For 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 deocde this base64 string and convert it into a file and save it on the device...

can someone help me?

thank you all =)


回答1:


You can try this:

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

Where:

  • filepath: Path to the new file
  • base64String: Your base64 string that you want to convert


来源:https://stackoverflow.com/questions/36578863/how-to-decode-base64-string-and-convert-it-into-pdf-jpg-and-save-it-in-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!