1

I've been researching many posts and tutorials found on Google or Stack Overflow and nobody has really used JSONParser to upload an image. All the code I found was used to do so with websites instead of Android.

How can I use JSONParser to upload an image?

I wanted to be able to either upload from the gallery or take a photo by camera and upload it directly in my app.

The JSONParser class looks like this:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String result = "";
    static String json = "";

    // constructor
    public JSONParser() {

    }


    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if(method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

We can do it by passing in the parameters but seems nobody is using it. Is it impossible or is there a bug in the implementation?

1 Answer 1

2

To upload a file to the server (image, audio etc) you may want to use MultipartEntity. Find online and download those two libraries: httpmime-4.0.jar and apache-mime4j-0.4.jar and add them to the project. Here is an example of how to use it:

public void doUpload(File fileToUpload)
{
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httppost = new HttpPost(URL_UPLOAD_HERE);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("imgType", new StringBody(imgType));
        entity.addPart("imgFile", new FileBody(fileToUpload));

        httppost.setEntity(entity);

         //------------------ read the SERVER RESPONSE
        HttpResponse response = httpclient.execute(httppost);
        StatusLine statusLine = response.getStatusLine();
        Log.d("UploaderService", statusLine + "");
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity resEntity = response.getEntity();
            InputStream content = resEntity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while (( line = reader.readLine()) != null)
            {
                Log.i("Debug","Server Response " + line);

                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(line);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }
            }
            reader.close();
        } else {
            Log.e(UploaderService.class.toString(), "Failed to upload file");
        }  

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and in the server side you can use these entities identifier's names "imgFile" and "imgType" to retrieve the file and process it. Notice that using those libraries you can also send another parameters along with your file as I did in the example (attached a 'imgType' String to the entity).

Consider running this code in a separate thread like AsyncTask

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.