unable to post base64 converted image to rest serv

2019-09-05 00:54发布

问题:

I've written a code that selects image from gallery and convert it into a BASE64 string. as the selected images was too large the string is too big to be posted.

I have compressed the image so that the length of the string could be reduced. but still the length of the string is still large.

The code that i used is as follows, This function sets the selected image in an imageView and

if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        sPicturePath = cursor.getString(columnIndex);
        cursor.close();
        imageView = (ImageView) findViewById(R.id.imageView);

        Bitmap bm = ShrinkBitmap(sPicturePath, 300, 300);
        imageView.setImageBitmap(bm);

        /**
         * Compute size of the image selected image
         */
        File file = new File(sPicturePath);
        if (file.exists()) {

            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            System.out.println("megabytes : " + megabytes);
            Log.d("size", String.valueOf(megabytes));
        }

        imageView.setImageBitmap(BitmapFactory.decodeFile(sPicturePath));

        Bitmap bm1 = BitmapFactory.decodeFile(sPicturePath);
        //CropImage();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm1.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
        byte[] byteArrayImage = baos.toByteArray();

        encodedString = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
        //Toast.makeText(getApplicationContext(), encodedString, Toast.LENGTH_SHORT).show();
        String length = String.valueOf(encodedString.length());
        //Toast.makeText(getApplicationContext(),lenght,Toast.LENGTH_SHORT).show();

        Log.d("encodedString", encodedString);
        Log.d("length", length);

ShrinkBitmap.java

Bitmap ShrinkBitmap(String file, int width, int height) {
    BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);

    int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
    int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);

    if (heightRatio > 1 || widthRatio > 1) {
        if (heightRatio > widthRatio) {
            bmpFactoryOptions.inSampleSize = heightRatio;
        } else {
            bmpFactoryOptions.inSampleSize = widthRatio;
        }
    }

    bmpFactoryOptions.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
    return bitmap;
}

What i want to achieve is to select an image from gallery convert it into a BASE64 string and post it through a REST service.

回答1:

A GET request has URL length restrictions. You need to send the file using MultipartEntity using HttpURLConnection. You need to create a post request.

If your filename is image.jpg.

Bitmap bitmap = ...;
String filename = "image.jpg";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename);

MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("picture", contentPart);
String response = multipost("http://server.com", reqEntity);

And this is the multipost function.

private static String multipost(String urlString, MultipartEntity reqEntity) {
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
        conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

        OutputStream os = conn.getOutputStream();
        reqEntity.writeTo(conn.getOutputStream());
        os.close();
        conn.connect();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return readStream(conn.getInputStream());
        }

    } catch (Exception e) {
        Log.e(TAG, "multipart post error " + e + "(" + urlString + ")");
    }
    return null;        
}

private static String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuilder builder = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return builder.toString();
}

More info at this SO thread.