使用json数据发送imageview base64编码的字符串

时间:2013-11-28 05:23:17

标签: android mysql json

我想将imageview android映像发送到我的服务器url并将其存储到我的服务器数据库(phpmyadmin)中。 当我试图插入简单的字符串然后它工作,但当它是图像视图然后它不..请帮助..这是我的代码

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

}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
}