获取上传到服务器的文件路径

时间:2014-07-29 06:04:56

标签: android file-upload

我正在创建一个应用程序,我想将图像发送到Web Server。因为我正在使用相机和图库intent。现在我想要的是获取用户选择的图像的路径,以便我可以上传到服务器。现在我怎么能得到路径???

代码

if (userSelection.equals("Gallery")) {
                            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, 0);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Camera")) {
                            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 1);
                            btChooseDoc.setText("Choose File");
                        }

                        if (userSelection.equals("Other")) {
                            intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("file/*");
                            startActivityForResult(intent, 2);
                            btChooseDoc.setText("Choose File");
                        }
                    }

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        Bitmap camera;
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();

        if (requestCode == 1 && resultCode == getActivity().RESULT_OK) {

            camera = (Bitmap) data.getExtras().get("data");
            camera.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
            galleryImage = Bitmap.createScaledBitmap(galleryImage, 150, 150, false);
            image.setImageBitmap(camera);


        }


        if (requestCode == 0 && resultCode == getActivity().RESULT_OK) {

            galleryUri = data.getData();
            try {
                galleryImage = decodeUri(getActivity(), galleryUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            galleryImage.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
            galleryImage = Bitmap.createScaledBitmap(galleryImage, 150, 150, false);
            image.setImageBitmap(galleryImage);


        }

    }

2 个答案:

答案 0 :(得分:0)

您好,您可以尝试使用以下代码从库中获取所选图像的路径..

打开图库...

private static int RESULT_LOAD_IMAGE = 1; //variable declared globally
ButtonClickListener()

上的

Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, RESULT_LOAD_IMAGE);

活动结果:

 if(data != null){

    Uri selectedImage = data.getData(); 
    String[] filePathColumn = { MediaStore.Images.Media.DATA }; 
    Cursor cursor = context.getContentResolver().query(selectedImage,filePathColumn, null, null, null); 

    cursor.moveToFirst(); 
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
    String picturePath = cursor.getString(columnIndex); //path of image...

    cursor.close();
    }

答案 1 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

<强> activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/select_photo"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Gallery"/>

        <Button
            android:id="@+id/take_photo"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Camera"/>
    </LinearLayout>
</LinearLayout>

<强> MainActivty.java

public class MainActivty extends Activity {

    private static final int CAMERA_REQUEST = 1;
    private static final int RESULT_LOAD_IMAGE = 2;
    Button camera;
    Button gallery;
    ImageView imageView;
    private String imgPath;

    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.launcher);
        gallery = (Button) findViewById(R.id.select_photo);
        camera = (Button) findViewById(R.id.take_photo);
        imageView = (ImageView) findViewById(R.id.imageView);


        gallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""), RESULT_LOAD_IMAGE);
            }
        });

        camera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAMERA_REQUEST);
            }
        });

    }

    public Uri setImageUri() {
        // Store image in dcim
        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
        Uri imgUri = Uri.fromFile(file);
        this.imgPath = file.getAbsolutePath();
        return imgUri;
    }

    public String getImagePath() {
        return imgPath;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RESULT_LOAD_IMAGE) {
                String imagePath = getAbsolutePath(data.getData());
                imageView.setImageBitmap(decodeFile(imagepath));
                // use imagePath to upload image on server
            } else if (requestCode == CAMERA_REQUEST) {
                String imagePath = getImagePath();
                imageView.setImageBitmap(decodeFile(imagePath));
                // use imagePath to upload image on server
            }
        }

    }

    public String getAbsolutePath(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = uri.getLastPathSegment().split(":")[1];
            final String[] imageColumns = {MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
            Uri tempUri = getUri();
            Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
                    MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
            if (imageCursor.moveToFirst()) {
                return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

    }

    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }

    public Bitmap decodeFile(String path) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 1024;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}

注意:请不要忘记AndroidManifest.xml中的此权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />