How To Decode Base64 String And Convert It Into Pdf/jpg And Save It In Storage
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 u
Solution 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 filebase64String:
Your base64 string that you want to convert
Solution 2:
Give READ_STORAGE and Write_STORAGE Permission in Manifest and dont forget for RunTime Permission.
publicstaticvoidstoretoPdfandOpen(Context context, String base) {
Stringroot= Environment.getExternalStorageDirectory().toString();
Log.d("ResponseEnv",root);
FilemyDir=newFile(root + "/WorkBox");
if (!myDir.exists()) {
myDir.mkdirs();
}
Randomgenerator=newRandom();
intn=10000;
n = generator.nextInt(n);
Stringfname="Attachments-" + n + ".pdf";
Filefile=newFile(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStreamout=newFileOutputStream(file);
byte[] pdfAsBytes = Base64.decode(base, 0);
out.write(pdfAsBytes);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Filedir=newFile(Environment.getExternalStorageDirectory(), "WorkBox");
FileimgFile=newFile(dir, fname);
IntentsendIntent=newIntent(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);
}
Post a Comment for "How To Decode Base64 String And Convert It Into Pdf/jpg And Save It In Storage"