Search code examples
androidandroid-asynctaskandroid-image

How to handle OutOfMemoryError exception while sending the large size images to server in Android


I am attaching 3 images (each 4.8Mb) and posting to server. While processing the 3rd image I am getting the "OutOfMemorryError". Below is the code snippet where I get the above error.

dos.write(buffer, 0, bufferSize);

I am facing the execption only in note 2, OS version 4.4.2

Below is the complete code snippet written for processing images.

for (int i = 0; i < attachmentUri.size(); i++) {
    String fileName ="attachment"+(i+1);
    File file = new File(attachmentUri.get(i));
    if (file.exists()) {
        dos.writeBytes("--" + Constants.IMAGE_BOUNDRY + LINE_FEED);
        uploadAttachments(dos, fileName,attachmentUri.get(i), LINE_FEED);
    } else {
        Log.i("Attachment not found");
    }
}

void uploadAttachments(DataOutputStream dos,String filename,String filePath,String lineEnd) {
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    try {
        FileInputStream inputStream = new FileInputStream(filePath);
        dos.writeBytes("Content-Disposition: form-data; name=\""+ filename + "\";filename=\""+ (filePath.substring(filePath.lastIndexOf("/")+1)) + "\"" + lineEnd + "Content-Type: image/jpeg; charset=UTF-8" + lineEnd); 
        dos.writeBytes(lineEnd);
        bytesAvailable = inputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = inputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = inputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = inputStream.read(buffer, 0, bufferSize);
        }
        dos.writeBytes(lineEnd);
        inputStream.close();
    } catch (IOException ioe){
        Log.e(e.getMessage());
    }
}

How to resolve the issue?


Solution

  • Try this answer on stackoverflow

    URLConnection connection = _url.openConnection();
            HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
            httpConnection.setConnectTimeout(45000);
            httpConnection.setReadTimeout(45000);
            httpConnection.setChunkedStreamingMode(1024);
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.setRequestMethod("PUT");
            httpConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + Constants.IMAGE_BOUNDRY);
            httpConnection.connect();