1

i am sending file like image,pdf etc to server . some time it giving me out of memory . so how i can Compress file byte[] or ant other way

my code to get byte[] is

 private byte[] GetbuildArray(String filePath) throws IOException {

    File file = new File(filePath);
    InputStream is = new FileInputStream(file);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;
    byte[] data = new byte[(int) file.length()];
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(bos);

    String filename = filePath.substring(filePath.lastIndexOf("/") + 1);

    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
    dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\""
            + filename + "\"" + lineEnd);
    dataOutputStream.writeBytes(lineEnd);

    ByteArrayInputStream fileInputStream = new ByteArrayInputStream(buffer.toByteArray());
    int bytesAvailable = fileInputStream.available();

    int maxBufferSize = bytesAvailable;
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffers = new byte[bufferSize];

    // read file and write it into form...
    int bytesRead = fileInputStream.read(buffers, 0, bufferSize);

    while (bytesRead > 0) {
        dataOutputStream.write(buffers, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffers, 0, bufferSize);
    }

    dataOutputStream.writeBytes(lineEnd);
    dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    return bos.toByteArray();
}

so in this i can avoid outofmemory error

andro
  • 1,007
  • 1
  • 14
  • 32
  • I don't think byte[] is your issue, i may be wrong but have a look at this SO Question: http://stackoverflow.com/questions/10290535/unable-to-write-into-dataoutputstream-beyond-a-specific-size-outofmemoryerror – SteedsOfWar Apr 13 '16 at 10:19

2 Answers2

0

If you want to transfer big files to server transferring them as a big bytestream over HTTP may not be a very good solution. You should consider some other protocol like ftp.

There are multiple client libraries for android to do ftp upload. You may want to look at those.

If you still want to use bytes, maybe you can upload it by chunks say a payload of 4KB at once with some metadata to recognize the file and chunk start index and you can stitch the file on the server

Abhishek Sinha
  • 435
  • 4
  • 12
0
int maxBufferSize = bytesAvailable;. 

Well if that is 2 MB (2mb is 2 milli bit dont you lnow?) then you have your memory problem. Just take a buffer of 8192 bytes and read bytes in and write bytes out in a loop

greenapps
  • 11,154
  • 2
  • 16
  • 19