android - 如何使用 JSONParser 实现上传图片的功能?

标签 android json image upload

我一直在研究在 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;
    }
}

我们可以通过传入参数来实现,但似乎没有人使用它。是不可能还是实现有bug?

最佳答案

要将文件(图像、音频等)上传到服务器,您可能需要使用 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 这样的单独线程中运行这段代码

关于android - 如何使用 JSONParser 实现上传图片的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15574050/

相关文章:

css - 内部链接 <li> 无效

android - 如果另一个 TextView 太长,如何在新行中移动 TextView

带有提示的编辑文本中的 Android 辅助功能

json - 简单的 node.js 应用程序中的高 RAM 使用率

json - 发布字符串会导致 Express 主体解析器抛出 SyntaxError

json - Symfony 3 API REST - try catch JSON 响应格式的异常

css - 如何使用 CSS 编辑已安装的 WordPress slider 插件的样式?

java - 为什么 Gridlayout 会在某个点将 View 移出视线

android - APP_CMD_WINDOW_RESIZED 未被调用但 native 窗口已调整大小

html - 有一个较小的图像然后 div 拉伸(stretch)以填充 div 的区域而不会破坏图像比例