1

我一直在研究 Google 或 Stack Overflow 上JSONParser的许多帖子和教程,但没有人真正习惯于上传图片。我发现的所有代码都用于网站而不是 Android。

如何使用JSONParser上传图片?

我希望能够从画廊上传或通过相机拍照并直接上传到我的应用程序中。

该类JSONParser如下所示:

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;
    }
}

我们可以通过传入参数来做到这一点,但似乎没有人使用它。是不可能的还是实施中有错误?

4

1 回答 1

2

要将文件上传到服务器(图像、音频等),您可能需要使用 MultipartEntity。在线查找并下载这两个库:httpmime-4.0.jarapache-mime4j-0.4.jar并将它们添加到项目中。以下是如何使用它的示例:

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();
    }
}

在服务器端,您可以使用这些实体标识符的名称“imgFile”和“imgType”来检索文件并进行处理。请注意,使用这些库,您还可以像我在示例中所做的那样随文件一起发送另一个参数(将“imgType”字符串附加到实体)。

考虑在单独的线程中运行此代码,例如 AsyncTask

于 2013-03-22T15:45:02.227 回答