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

时间:2016-05-31 12:49:53

标签: android android-asynctask android-image

我附加了3张图片(每张4.8Mb)并张贴到服务器上。在处理第3张图片时,我收到“OutOfMemorryError”。 以下是我收到上述错误的代码段。

dos.write(buffer, 0, bufferSize);

我只在注释2,操作系统版本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());
    }
}

如何解决问题?

1 个答案:

答案 0 :(得分:1)

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