DevAndroid
DevAndroid

Reputation: 99

Upload more then 5 MB using HttpURLConnection leads Out of Memory Error

I need the solution for how to upload more then 5 MB to server, since it can upload around 5MB , and also I have searched many threads in Stackoverflow I couldn't get the solution for uploading more than 5MB using HttpURLConnection.

I have use the below code to write to stream,

long lenghtOfFile = file2.length();
                    long total = 0;
                    try {
                        FileInputStream is = null;
                        java.nio.ByteBuffer bb = null;
                        try {
                            is = new FileInputStream(file2);

                            java.nio.channels.FileChannel fc = is.getChannel();
                            bb = java.nio.ByteBuffer.allocate(10000);
                            byte[] bytes;
                            while (fc.read(bb) >= 0) {
                                bb.flip();
                                // save the part of the file into a chunk
                                bytes = bb.array();
                                bb.clear();
                                Log.i("ByteLength", "" + bb.array().length);
                                output.write(bytes, 0, bytes.length);
                                total += bytes.length;
                                Log.i("total", "" + lenghtOfFile);
                                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                                output.flush();
                                System.gc();

                            }

                        } catch (Exception e) {

                        } finally {
                            try {
                                is.close();
                                output.flush();
                                bb.clear();
                            } catch (Exception e) {

                            }
                        }

                    } catch (Exception e) {
                    }

Please check this snippet and give me the solution to overcome this problem.

Upvotes: 0

Views: 2919

Answers (1)

idiottiger
idiottiger

Reputation: 5177

suggestion before upload, you can using:

HttpURLConnection.setFixedLengthStreamingMode(int size)

method to ensure the upload file size.

ps: see the api document: http://developer.android.com/reference/java/net/HttpURLConnection.html#setFixedLengthStreamingMode%28int%29

Upvotes: 3

Related Questions