如何在 Android 中将大尺寸图像发送到服务器时处理 OutOfMemoryError 异常

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

我附上了 3 张图片(每张 4.8Mb)并发布到服务器。在处理第三张图像时,我得到 "OutOfMemorryError"。 下面是出现上述错误的代码片段。

dos.write(buffer, 0, bufferSize);

我只在注释 2 中遇到异常,OS 版本 4.4.2

下面是为处理图像而编写的完整代码片段。

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());
    }
}

如何解决这个问题?

Whosebug

上试试这个答案
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();