Android - 如何将Imageview中的图像上传到远程服务器?

时间:2014-03-31 09:18:31

标签: android android-imageview

我有以下代码从图库中选取图像并将其放到图像视图中,现在我需要将其上传到服务器上!我在网上浏览了很多代码,但大多数代码都没有用。任何人都可以帮我这个吗?

public class MainActivity extends Activity {

     ImageView viewImage;
        Button b;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b=(Button)findViewById(R.id.btnSelectPhoto);
            viewImage=(ImageView)findViewById(R.id.viewImage);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectImage();
                }
            });
        }




          private void selectImage() {

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

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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);
                }
            }
        }   
    }





activity_main.xml code :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/LinearLayout1"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:padding="10dp" >

  <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="center"
          android:padding="5dp" >

    <Button
            android:id="@+id/btnSelectPhoto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Select Photo" />

  </LinearLayout>

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical"
      android:padding="10dp" >

      <ImageView
          android:id="@+id/viewImage"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_weight="0.86"
          android:src="@drawable/ic_launcher" />

      <Button
          android:id="@+id/button1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:text="Upload" />
  </LinearLayout>

</LinearLayout> 

3 个答案:

答案 0 :(得分:6)

使用以下代码行并将base64字符串发送到服务器:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send  in Bitmap form
byte[] byteArray = baos.toByteArray();

String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

答案 1 :(得分:0)

将您的图像编码为Base64,然后在服务器中对其进行解码 http://developer.android.com/reference/android/util/Base64.html

答案 2 :(得分:0)

这是我上传图片到服务器的代码,以及它的工作原理。您需要导入httpmime jar

PHP代码

$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    echo $_POST["contentString"]."\n";
    echo  "File path = ".$uploads_dir;
    move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
} else {
    echo "\n Upload Error";
    echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
    print_r($_FILES);

JAVA代码

HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php");

File file = new File(filePath);

MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
entity.addPart("userfile",contentFile);

StringBody contentString = new StringBody("This is contentString");
entity.addPart("contentString",contentString);

postMethod.setEntity(entity);
HttpResponse response = client.execute(postMethod);
HttpEntity httpEntity = response.getEntity();
String state = EntityUtils.toString(httpEntity);