2013-03-22 1 views
1

Google이나 스택 오버플로에서 발견 된 많은 게시물과 자습서를 연구했으며 아무도 실제로 이미지를 업로드하는 데 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; 
    } 
} 

우리는 매개 변수를 전달하여 그것을 할 수 있지만 아무도 그것을 사용하지 않는 것 같다 :

JSONParser 클래스는 다음과 같습니다. 구현이 불가능하거나 버그가 있습니까?

답변

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'String 첨부).

이 코드를 AsyncTask와 같은 별도의 스레드에서 실행하는 것을 고려하십시오.

관련 문제