Search code examples
androidamazon-s3httpurlconnection

How to upload image using presignedurl from aws S3 server in android


I am trying to upload image to S3 bucket from presigned url it is giving ssl exception error connection closed by peer

here is my code

public int upload(String filePath, URL url) {
 Bitmap bm = BitmapFactory.decodeFile(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            byte[] fileBytes = bos.toByteArray();

            connection = (HttpURLConnection) url.openConnection();

            connection.setDoOutput(true);
            connection.setRequestMethod("PUT");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/octet-stream"); 

            OutputStream output = connection.getOutputStream();
            InputStream input = new ByteArrayInputStream(fileBytes);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            output.flush();

            return connection.getResponseCode();
}

Solution

  • Finally I figured it out, here is the code to send image to S3 using presigned URL

    try {
    
                Bitmap bm = BitmapFactory.decodeFile(fileBytes);
                connection = (HttpsURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("PUT");
                connection.setRequestProperty("Content-Type", "application/octet-stream"); // Very important ! It won't work without adding this!
    
                OutputStream output = connection.getOutputStream();
    
    
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG, 50, output);
                output.flush();
    
                int response = connection.getResponseCode();
    
                return connection.getResponseCode();
            } catch (IOException e) {
                e.printStackTrace();
            }