2013-11-28 3 views
1

이미지 뷰 안드로이드 이미지를 내 서버 URL로 보내고이를 내 서버 데이터베이스 (phpmyadmin)에 저장하고 싶습니다. 내가 간단한 문자열을 삽입하기 위해 노력하고 그것은 작동하지만 다음 이미지보기를 때 그것은 ..이 당신은 이미지를 업로드 다중 엔티티를 사용해야합니다 내 코드json 데이터를 사용하여 imageview base64 인코딩 된 문자열을 보냅니다.

public class AddnewActivity extends Activity { 

     ImageView iv; 

    public static final int PHOTO_PICKER_ID = 0; 
    EditText name; 
    EditText comments; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_addnew); 
     // Show the Up button in the action bar. 
     setupActionBar(); 
     iv=(ImageView) findViewById(R.id.imageView1); 

     ImageButton imgb= (ImageButton) findViewById(R.id.imageButton1); 
     imgb.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
      try{ 
       Intent intent = new Intent(); 
       intent.setType("image/*"); 
       intent.setAction(Intent.ACTION_GET_CONTENT); 
       startActivityForResult(Intent.createChooser(intent,"Complete action using"), PHOTO_PICKER_ID); 
      } 
      catch(Exception e){} 

      } 
     }); 



     Button save=(Button) findViewById(R.id.button1); 
     save.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

      try{ 


       Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher); 
       ByteArrayOutputStream stream=new ByteArrayOutputStream(); 
       bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); 
       byte[] imageByteArray=stream.toByteArray(); 

       String img_str = Base64.encodeToString(imageByteArray, 0); 


      name=(EditText) findViewById(R.id.editText1); 
      String nm=name.getText().toString(); 
      comments=(EditText) findViewById(R.id.editText2); 
      String com=comments.getText().toString(); 

      if("".equals(nm) || "".equals(com)){ 

      Toast.makeText(getApplicationContext(), "Empty field detected", Toast.LENGTH_SHORT).show(); 
      } 
      else{ 

       try { 
        JSONObject json = new JSONObject(); 
        json.put("name", nm); 
        json.put("comments", com); 
        json.put("img", img_str); 

        HttpClient client = new DefaultHttpClient(); 
        String url = "http://myservername/parser/json_req.php"; 

        HttpPost request = new HttpPost(url); 
        request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8"))); 
        request.setHeader("json", json.toString()); 
        HttpResponse response = client.execute(request); 
        HttpEntity entity = response.getEntity(); 

        if (entity != null) { 
         InputStream instream = entity.getContent(); 


         Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_SHORT).show(); 
        } 
       name.setText(null); 
       comments.setText(null);  


       } catch (Throwable t) { 

        Toast.makeText(getApplicationContext(), "Request failed: " + t.toString(), Toast.LENGTH_SHORT).show(); 
       } 


      } 

      }catch(Exception e){} 

      } 
     }); 

    } 

    /** 
    * Set up the {@link android.app.ActionBar}, if the API is available. 
    */ 
    @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    private void setupActionBar() { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      getActionBar().setDisplayHomeAsUpEnabled(true); 
     } 
    } 








     @Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

      Uri currImageURI = null; 
      if (resultCode == Activity.RESULT_OK) { 
       if (data != null) { 
        currImageURI = data.getData(); 
       } 
       if (currImageURI == null) { 
        String filePath = Environment.getExternalStorageDirectory() 
          + ""; 
        filePath = filePath + File.separator + "temp_img.jpg"; 
        File f = new File(filePath); 

        currImageURI = Uri.fromFile(f); 
       } 

       ContentResolver cr = getContentResolver(); 
       Bitmap bitmap; 
       try { 
        bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,currImageURI); 
        iv.setImageBitmap(bitmap); 
       } catch (Exception e) { 
        Log.e("Camera", e.toString()); 
       } 
      } 
     } 

















    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.addnew, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case android.R.id.home: 
      // This ID represents the Home or Up button. In the case of this 
      // activity, the Up button is shown. Use NavUtils to allow users 
      // to navigate up one level in the application structure. For 
      // more details, see the Navigation pattern on Android Design: 
      // 
      // http://developer.android.com/design/patterns/navigation.html#up-vs-back 
      // 
      NavUtils.navigateUpFromSameTask(this); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

} 
+0

당신이 받고있는 오류를 게시 할 수 있습니까? – MAkS

답변

1

입니다 도움이 not..please 않습니다. 다음과 같은 는 : -

여기
public void postPicture(String path, File file) throws ParseException, IOException, XmlParseException { 
     HttpClient httpclient = new DefaultHttpClient(); 
     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
     HttpPost httppost = new HttpPost(path); 
     MultipartEntity mpEntity = new MultipartEntity(); 
     FileBody cbFile = new FileBody(file, "image/png"); 
     cbFile.getMediaType(); 
     mpEntity.addPart("userfile", cbFile); 
     httppost.setEntity(mpEntity); 
     HttpResponse response = httpclient.execute(httppost); 
    } 

http://useandgain.blogspot.in/2012/06/uploading-image-from-androidjava-using.html

+0

UI 스레드에서 네트워크 호출을해서는 안됩니다 .HttpResponse를 호출하려면 AsyncTask를 사용하십시오. response = httpclient.execute (httppost); – MAkS

+0

이 함수는 백그라운드 스레드 내에서 호출해야합니다. –

+0

asynck 작업 또는 스레드를 사용하십시오. –

0

먼저 사진을 압축 한 후 64 기수로 비트 맵 (사진)을 변환해야하고, 아래의 코드를 사용하기위한 간단한 튜토리얼 마지막으로 서버로 보냅니다.

public String webServiceCall(String photo) { 

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

    nameValuePairs 
      .add(new BasicNameValuePair("photo", photo)); 
    String jsonresponse = getData(nameValuePairs); 
    return jsonresponse; 
} 

public String getData(ArrayList<NameValuePair> params) { 
    try { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 
       10000); 
     HttpPost httpPost = new HttpPost(url); 
     httpPost.setEntity(new UrlEncodedFormEntity(params)); 
     Log.d("In request :", params.toString()); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     Log.d("Response Output", httpResponse.toString()); 

     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 
     Log.d("Response Output", is.toString()); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (Exception 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(); 
     jsonResponse = sb.toString(); 
     Log.e("JSON reading ", jsonResponse); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 
    return jsonResponse; 
} 
관련 문제