hossam rakha
hossam rakha

Reputation: 253

How to convert file to base64 in Android?

I have enabled the user to select a specific file from his device the extension of the file is .txt , and I'm using MaterialFilePicker library for it , now how to convert this file to string base64 so I can send the file to the server. if there's another library or another way to do it please recommend me to use it. this the code I tried but it didn't work out , thanks.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case PERMISSIONS_REQUEST_CODE: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFilePicker();
            } else {
                showError();
            }
        }
    }
}


// FILE PICKER
private void checkPermissionsAndOpenFilePicker() {
    String permission = Manifest.permission.READ_EXTERNAL_STORAGE;

    if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            showError();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, PERMISSIONS_REQUEST_CODE);
        }
    } else {
        openFilePicker();
    }
}

private void showError() {
    Toast.makeText(this, "Allow external storage reading", Toast.LENGTH_SHORT).show();
}

   private void openFilePicker() {
    new MaterialFilePicker()
            .withActivity(this)
            .withRequestCode(FILE_PICKER_REQUEST_CODE)
            .withHiddenFiles(true)
            .withTitle("Sample title")
            .start();
}
  @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
        String path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
        if (path != null) {
            Log.d("Path: ", path);
            file = new File(path);
            fileStr = String.valueOf(file);



            Toast.makeText(this, "Picked file: " + file, Toast.LENGTH_LONG).show();
        }
    }
}

//convert the file path to base64
public static String encodeImage(String path) {
    File imagefile = new File(path);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Bitmap bm = BitmapFactory.decodeStream(fis);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
    byte[] b = baos.toByteArray();
    String encImage = Base64.encodeToString(b, Base64.DEFAULT);
    if (fis != null) {
        try {
            fis.close();
            if (baos != null)
                baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Base64.de
    return encImage;

}

Upvotes: 1

Views: 5081

Answers (2)

Arnold Brown
Arnold Brown

Reputation: 1433

Try this:

        File file = new File("myfile.txt");

        //convert file to byte[]
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(file);
        bos.close();
        oos.close();
        byte[] bytearray = bos.toByteArray();

        //convert byte[] to file
        ByteArrayInputStream bis = new ByteArrayInputStream(bytearray);
        ObjectInputStream ois = new ObjectInputStream(bis);
        File fileFromBytes = null;
        fileFromBytes = (File) ois.readObject();
        bis.close();
        ois.close();

        System.out.println(fileFromBytes);

Note: Don't forget to handle the exception(try/catch)

Upvotes: 0

Manoj Perumarath
Manoj Perumarath

Reputation: 10244

First read the file to a byte array, and then use

  Base64.encodeToString(byte[], int)

to convert it to a Base64 string.

Upvotes: 3

Related Questions