2013-11-28 105 views
1

我想將imageview android圖像發送到我的服務器url並將其存儲到我的服務器數據庫(phpmyadmin)中。 當I M試圖插入簡單的字符串,然後它工作,但是當它是圖像視圖,然後它not..please幫助..這是我的代碼使用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

必須使用多實體上傳圖片。 像如下: -

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線程上進行網絡調用。使用AsyncTask調用HttpResponse response = httpclient.execute(httppost); – MAkS

+0

您必須在後臺線程中調用此函數。 –

+0

使用asynck任務或線程。 –

0

使用下面的代碼,首先你要壓縮的照片,然後轉換成位圖(照片)爲Base64和最後發送給服務器。

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