views:

231

answers:

2

I want to upload a big file to a server from a Nokia phone and I use code below. This code works fine for small files. When I want to upload a bigger file (about 10mb) I get an out of memory message. Does anyone knows how can I transform this code to upload the file using multiple httpConnections, sending a chunk of the file with each connection. Let's assume the server supports this.

fc = (FileConnection)Connector.open("file:///myfile", Connector.READ);
is = fc.openInputStream();

// opening http connection and outputstream
HttpConnection http = (HttpConnection)Connector.open(url, Connector.WRITE);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", type);
http.setRequestProperty("Connection", "close");

OutputStream os = http.openOutputStream();


int total = 0;

while (total < fileSize) {      
    byte b[] = new byte[1024];   
    int length = is.read(b, 0, 1024);

    os.write(b, 0, length);
    total += length;
}
os.flush();


int rc = http.getResponseCode();
os.close();
http.close();
+1  A: 

Try moving the os.flush() call inside the while loop, so the buffer is flushed each time. As it stands at the moment your entire file is being read into memory before being sent over the wire.

If this doesn't solve it, I would suggest running the code in an emulator using a profiler so you can better understand where the memory is being used up.

Chris Harcourt
A: 

Try to move buffer initialization byte b[] = new byte[1024]; before your while loop - you don't need to recreate it everytime. And try putting System.gc() inside the loop - it may help (or may not).

Also, some devices may try to put entire file into memory when you call fc.openInputStream

Pavel Alexeev