如何在android中将文件转换为base64?

时间:2017-11-09 11:21:38

标签: android android-studio

我已经启用了用户从他的设备中选择一个特定文件,该文件的扩展名是.txt,而我正在使用MaterialFilePicker库,现在如何将此文件转换为字符串base64,以便我可以发送该文件到服务器。 如果有其他图书馆或其他方式,请建议我使用它。 这个我试过的代码,但它没有成功,谢谢。

@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;

}

2 个答案:

答案 0 :(得分:2)

首先将文件读取为字节数组,然后使用

  Base64.encodeToString(byte[], int)

将其转换为Base64字符串。

答案 1 :(得分:0)

试试这个:

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

        //convert file to byte[]
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        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);

注意: 不要忘记处理异常(尝试/捕获)