如何解码base64字符串并将其转换为PDF/JPG格式并保存到存储中。

12
我想要解码一个base64字符串并将其转换为文件(如PDF / JPG),并将其保存到设备中,例如在 (/storage/emulated/0/Download/file.pdf) 中。对于编码文件,我使用以下代码:

我想将一个base64字符串解码成文件,并且保存到设备上,例如:(/storage/emulated/0/Download/file.pdf)。对于编码文件,我使用以下代码:

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();
    }
现在,我想解码这个base64字符串并将它转换成一个文件,并保存在设备上。
2个回答

26

你可以尝试这样做:

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

其中:

  • filepath:新文件的路径
  • base64String:您想要转换的base64字符串

2
在清单文件中赋予READ_STORAGE和WRITE_STORAGE权限,并且不要忘记运行时权限。
 public static void storetoPdfandOpen(Context context, String base) {



    String root = Environment.getExternalStorageDirectory().toString();

    Log.d("ResponseEnv",root);

    File myDir = new File(root + "/WorkBox");
    if (!myDir.exists()) {
        myDir.mkdirs();
    }

    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);

    String fname = "Attachments-" + n + ".pdf";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {

        FileOutputStream out = new FileOutputStream(file);
        byte[] pdfAsBytes = Base64.decode(base, 0);
        out.write(pdfAsBytes);
        out.flush();
        out.close();


    } catch (Exception e) {
        e.printStackTrace();
    }

    File dir = new File(Environment.getExternalStorageDirectory(), "WorkBox");
    File imgFile = new File(dir, fname);
    Intent sendIntent = new Intent(Intent.ACTION_VIEW);

    Uri uri;
    if (Build.VERSION.SDK_INT < 24) {
        uri = Uri.fromFile(file);
    } else {
        uri = Uri.parse("file://" + imgFile); // My work-around for new SDKs, causes ActivityNotFoundException in API 10.
    }

    sendIntent.setDataAndType(uri, "application/pdf");
    sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(sendIntent);

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接