3

Smaller size file are uploaded to server successfully but when it come to larger files the below code throws out of memory error. any solution ?? . Thanks in advance.

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();
        }
Sai
  • 15,188
  • 20
  • 81
  • 121
  • Use some better HTTP client API, one that allows you to stream your body, rather than having to load the body into memory first. OkHttp [appears to be able to handle this](https://github.com/square/okhttp/wiki/Recipes#post-streaming). – CommonsWare Aug 20 '15 at 12:02
  • why are you using both an outputstream and a writer? wouldn't they interfere? – njzk2 Aug 20 '15 at 12:10

2 Answers2

8

use chunchedStreamingMode it will help you to chunk your data in specific size.

con.setChunkedStreamingMode(1024);

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

Community
  • 1
  • 1
3

I strongly recommend you to use an HTTPClient. In addition, you should consider using Apache Commons IO, more specifically the IOUtilsclass to copy your FileInputStream to the OutputStream (your remote call) using

IOUtils.copy(inputStream, outputStream);

This will avoid that you have to load the file into memory, thus avoiding OutOfMemory Exceptions. The file will basically be streamed from disk to the server.

Marc Giombetti
  • 819
  • 1
  • 8
  • 20