Androidファイル転送Base 64

1696 ワード

前提条件
今のプロジェクトは私达のピクチャーがアップロードする时Base 64を使ってピクチャーをアップロードすることを要求して、私のもとの方法はこのようです
Bitmap smallBitmap = null;
String base64Url = null;
try {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    options.inJustDecodeBounds = false;
    smallBitmap = BitmapFactory.decodeFile(filePath, options);
    byte[] photoData = BitmapUtil.bitmap2bytes(smallBitmap);
    base64Url = Base64.encodeToString(photoData, Base64.NO_WRAP);
} catch (Exception e) {
    e.printStackTrace();
    base64Url = "";
}


1.画像を取得するBitmap 2.Bitmapをbyte[]に変換する3.byte[]をstring**に変換する最初のステップでは次の値が大きくなり、最初のステップでは次の値が大きくなり、最初のステップでは次の値が大きくなります**例えば画像50 Kになり、ステップ2からステップ3で戻るstringが100 Kになります(携帯電話の画面の高さや画面密度によって異なります)
ソリューション
// https://mvnrepository.com/artifact/commons-codec/commons-codec base64 
compile group: 'commons-codec', name: 'commons-codec', version: '1.5'
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(bytes, 0, bytes.length);
    buf.close();
} catch (Exception e) {
    LogUtils.e("base64    byte64", e);
}
byte[] encodedBytes = org.apache.commons.codec.binary.Base64.encodeBase64(bytes);
byte[] decodedBytes = org.apache.commons.codec.binary.Base64.decodeBase64(encodedBytes);
String base64Url = Base64.encodeToString(decodedBytes, Base64.NO_WRAP);

1.gradleはapache社のBase 64ヘルプクラスを導入する2.上記のコードを使用すると、大きくなりますが、それほど大げさではありません.
最後に
画像をアップロードするにはBase 64を使わないほうがいいです.requestbody、multipartの2つを使ってみてください.私はまだ試したことがありません.