Java – OutputStream out of memory error when sending file to HTTP

OutputStream out of memory error when sending file to HTTP… here is a solution to the problem.

OutputStream out of memory error when sending file to HTTP

Smaller files are

successfully uploaded to the server, but when larger files are involved, the following code throws an out-of-memory error. Advance thanks ?? . any solution.

public void addFilePart(String fieldName, File uploadFile)
                throws IOException {
            String fileName = uploadFile.getName();
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append(
                    "Content-Disposition: form-data; name=\"" + fieldName
                            + "\"; filename=\"" + fileName + "\"")
                    .append(LINE_FEED);
            writer.append(
                    "Content-Type: "
                            + URLConnection.guessContentTypeFromName(fileName))
                    .append(LINE_FEED);
            writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();

FileInputStream inputStream = new FileInputStream(uploadFile);
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            inputStream.close();

writer.append(LINE_FEED);
            writer.flush();
        }

Solution

Use chunchedStreamingMode and it will help you chunk your data at a specific size.

con.setChunkedStreamingMode(1024);

This link can help you
Upload large file in Android without outofmemory error

Related Problems and Solutions