3

The following code uploads file to the server:

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public String uploadFileForStorage(String serverUrl, String filePath) {
StringBuilder responseMsg = new StringBuilder();
    try {
        final File file = new File(filePath);
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        HttpConnectionParams.setConnectionTimeout(httpParameters, UPLOAD_CONNECTION_TIME_OUT);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, UPLOAD_SOCKET_TIME_OUT);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);

        if (serverUrl.contains("?")) {
             serverUrl = Utils.getProperUrlWithOutEncode(serverUrl);
        }

        HttpPost postRequest = new HttpPost(serverUrl);
        FileBody bin = new FileBody(file);

        CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener() {
                        @Override
                        public void transferred(long num) {
                            total = total + num;
                        }
                    });
                    multipartContent.addPart(CUSTOM_FILE_TAG, bin);
                    postRequest.setEntity(multipartContent);
                    HttpResponse response = httpClient.execute(postRequest);
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                        String sResponse;
                        while ((sResponse = reader.readLine()) != null) {
                            responseMsg = responseMsg.append(sResponse);
                        }
                    } else {
                        responseMsg = responseMsg.append(String.valueOf(response.getStatusLine().getStatusCode()));
                    }
                } catch (Exception e) {
                    isError = true;
                }
                return responseMsg.toString();
            }

        }

Files are being uploaded from Tablet SDCard. The above code works fine with multiple Android Tablets like Samsung Galaxy Note 10.1 & Micromax Funbook 10 inch but crashes while uploading files in Samsung P6200. The crash doesnot immediately occur , but after 5-10% of uploading.

Previously , the upload was working fine on Samsung P6200 too . I made the factory reset of the tablet but the crash at upload persists. Also , OutOfMemoryException is not being shown in the logcat. The log shows NullPointerException in a class file which it shouldnot. Assuming the problem to be a HeapSize issue , how can I handle the issue.

Using the above code , I am able to upload file upto 400 MB from SDCard using SIM(3G / WiFi) with Android Tablets like Samsung Galaxy Note 10.1 & Micromax Funbook 10.

should adding the following line of code help ?

HttpConnectionParams.setSocketBufferSize(httpParameters, 8192); 
// or any value other than //8192
B770
  • 1,272
  • 3
  • 17
  • 34
chiranjib
  • 5,288
  • 8
  • 53
  • 82
  • 2
    Can you post logcat for the error case ? It might help pinpoint the error, but either way look at http://stackoverflow.com/questions/4455006/posting-a-large-file-in-android – Vrashabh Irde Jul 23 '13 at 15:55
  • 1
    "The log shows NullPointerException in a class file which it should not.". You really need to include information like this. – Reuben Scratton Jul 23 '13 at 17:40
  • Reuben Scratton : Actually getting a NullPointer exception in an Activity where the layout only includes a Button which when clicked will start the upload process. In scenarios where the upload process is successful , the NullPointerException is never thrown. Thats the reason for not entering the details in the question. I dont think the NullPointerException is the real cause for the crash else it would have been thrown in all the scenarios. – chiranjib Jul 24 '13 at 05:01
  • Try putting some Logs at suspected places like before loop inside loop and outside loop so by the logcat result you can get to know how much steps you have done successfully and where you app got crashed. – dinesh sharma Jul 26 '13 at 10:10
  • You should use Buffer to upload file. In your code, pls extends FileBody mFileBody = new FileBody(fileName) {writeTo()...}; – Luc Jul 28 '13 at 03:17

1 Answers1

0
                postRequest.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(postRequest);

If suspect heap issues , then you should check into the implementation / source of your httpclient. I guess that you are using apache client so you can check there.

There are 2 memory issues.

When the file tag gets mapped to memory ( prior to using the socket ) how big and what kind of buffer is used? You may have to dig into the code that maps the file to memory and make it conform to smaller available memory/ buffer size.

Once the socket goes into action for the upload, the client.execute uses another buffer cycle to read from the file memory and to write to the socket being used for the upload. In addition to playing with config on the socket buffer size, you may also want to try 'chunked-encoding' (streaming) with the upload. Dump your headers and you should be able to see whether the Mime Multipart form you use leads to http header of "chunked-encoding".

For chunked example with httpUrlConnection that would work with big uploads. find "ChunkedStreamingMode" in the source.

Robert Rowntree
  • 6,230
  • 2
  • 24
  • 43