如何在我的Web服务中上传用户图像

时间:2014-05-19 10:31:24

标签: java android json

爵士 我希望通过使用json的注册活动在webservice中添加user_image 这是我的注册活动 Signup.java

JSONParser jsonParser = new JSONParser();
private static String url = "http://www.mydomain.com/signup";


//Go To Login.java  
    login=(Button)findViewById(R.id.bktologin); 
    login.setOnClickListener(new View.OnClickListener() 
    {       
        @Override
        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(i);

        }
    }); 
// Close Login.java
    // button to add image
    viewImage=(ImageView)findViewById(R.id.imageView1);
    selectpic=(Button)findViewById(R.id.btnphoto);
    selectpic.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            selectImage();
        }
    });
}
    private void selectImage() {

        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(Signin.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo"))
                {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                }
                else if (options[item].equals("Choose from Gallery"))
                {
                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);

                }
                else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            bitmapOptions); 

                    viewImage.setImageBitmap(bitmap);

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {

                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.w("path of image from gallery......******************.........", picturePath+"");
                viewImage.setImageBitmap(thumbnail);
            }
        }





//Get all data and log in 
        signin=(Button)findViewById(R.id.register); 
        fullName=(EditText)findViewById(R.id.fname);
        userName=(EditText)findViewById(R.id.uname);
        dob=(EditText)findViewById(R.id.dob);
        age=(EditText)findViewById(R.id.age);
        viewImage=(ImageView)findViewById(R.id.imageView1);
        gender=(EditText)findViewById(R.id.gndr);
        interestIn=(EditText)findViewById(R.id.intrst);
        toMeet=(EditText)findViewById(R.id.tomeet);

    /*image=(ImageView)findViewById(R.id.imageView1);*/
    email=(EditText)findViewById(R.id.email);
    pwd=(EditText)findViewById(R.id.password);


    signin.setOnClickListener(new View.OnClickListener() 
    {           
        @Override
        public void onClick(View view) {

    //Check all fields      

             if(pwd.length()<4)
            {               
                Toast.makeText(Signin.this,"Please Enter minimum 4 letters in password", Toast.LENGTH_LONG).show();
                return;
            }

    //check connectivity        
             if(!isOnline(Signin.this))
            {                   
                Toast.makeText(Signin.this,"No network connection", Toast.LENGTH_LONG).show();
                return; 
            }

    //from login.java       
                new loginAccess().execute();
        }

    //code to check online details
    private boolean isOnline(Context mContext) {
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting())
      {
        return true;
        }
        return false;
    }
  //Close code that check online details        
  }); 
    //Close log in 
}


class loginAccess extends AsyncTask<String, String, String> {

protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(Signin.this);
    pDialog.setMessage("Sig in...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    String FullName=fullName.getText().toString();
    String UserName=userName.getText().toString();
    String DateOfBirth=dob.getText().toString();
    String Age=age.getText().toString();


    String Sex=gender.getText().toString();
    String InterestedIn=interestIn.getText().toString();
    String ToMeet=toMeet.getText().toString();


    String strimg = android.util.Base64.encodeToString(bytearr, 0, bytearr.length, Base64.DEFAULT);
    String Email=email.getText().toString();
    String Password=pwd.getText().toString();



    params.add(new BasicNameValuePair("fullName", FullName));
    params.add(new BasicNameValuePair("userName", UserName));
    params.add(new BasicNameValuePair("dob", DateOfBirth));
    params.add(new BasicNameValuePair("age", Age));
    params.add(new BasicNameValuePair("gender", Sex));
    params.add(new BasicNameValuePair("interestIn", InterestedIn));

    params.add(new BasicNameValuePair("toMeet", ToMeet));
    params.add(new BasicNameValuePair("image", strimg));
    params.add(new BasicNameValuePair("email", Email));
    params.add(new BasicNameValuePair("pwd", Password));




    JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);

    Log.d("Create Response", json.toString());

    try {

        if (json.has((TAG_SUCCESS))) {
            String status = json.getString(TAG_SUCCESS);
            if (status.equals("Success")) 
         {
          flag=0;   
          Intent i = new Intent(getApplicationContext(),Welcome.class);
    /*i.putExtra("Email",email);
          i.putExtra("Password", pwd);*/
          startActivity(i);
          finish();
         }
         else
         {
            // failed to Sign in
            flag=1;
        }
    }
    }catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
protected void onPostExecute(String file_url) {
    pDialog.dismiss();
    if(flag==1)
        Toast.makeText(Signin.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show();

}



 }

}

1 个答案:

答案 0 :(得分:0)

以字符串的形式发送图像,将其作为字节数组发送。 即。发送时将Bitmap图像传送到字节数组并发送,同时接收获取字节数组并将其转换为Bitmap图像。