Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 上傳圖片到伺服器的完整實作

本文實作一個簡單的圖片上傳功能:點擊「選擇圖片」從圖庫挑選圖片並顯示在下方 ImageView,再點擊「上傳圖片」即會上傳到指定伺服器。

佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="選擇圖片"
    android:id="@+id/selectImage"
    />
    <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="上傳圖片"
    android:id="@+id/uploadImage"
    />
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    />
</LinearLayout>

Upload Activity

public class Upload extends Activity implements OnClickListener {
    private static String requestURL = "https://192.168.1.212:8011/pd/upload/fileUpload.do";
    private Button selectImage, uploadImage;
    private ImageView imageView;

    private String picPath = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload);

        selectImage = (Button) this.findViewById(R.id.selectImage);
        uploadImage = (Button) this.findViewById(R.id.uploadImage);
        selectImage.setOnClickListener(this);
        uploadImage.setOnClickListener(this);

        imageView = (ImageView) this.findViewById(R.id.imageView);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.selectImage:
            /***
             * 調用android內置的intent來過濾圖片文件,同時也可以過濾其他的
             */
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, 1);
            break;
        case R.id.uploadImage:
            if (picPath == null) {
                Toast.makeText(Upload.this, "請選擇圖片!", 1000).show();
            } else {
                final File file = new File(picPath);
                if (file != null) {
                    String request = UploadUtil.uploadFile(file, requestURL);
                    uploadImage.setText(request);
                }
            }
            break;
        default:
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            /**
             * 當選擇的圖片不為空時,取得圖片的路徑
             */
            Uri uri = data.getData();
            Log.e(TAG, "uri = " + uri);
            try {
                String[] pojo = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(uri, pojo, null, null, null);
                if (cursor != null) {
                    ContentResolver cr = this.getContentResolver();
                    int colunm_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(colunm_index);
                    /***
                     * 這裡加判斷主要是為了第三方軟件選擇,例如使用第三方檔案管理器時,
                     * 選擇的檔案不一定是圖片,因此判斷副檔名,若是圖片格式才處理
                     */
                    if (path.endsWith("jpg") || path.endsWith("png")) {
                        picPath = path;
                        Bitmap bitmap = BitmapFactory.decodeStream(cr
                            .openInputStream(uri));
                        imageView.setImageBitmap(bitmap);
                    } else {
                        alert();
                    }
                } else {
                    alert();
                }
            } catch (Exception e) {
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void alert() {
        Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
            .setMessage("您選擇的不是有效的圖片")
            .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    picPath = null;
                }
            }).create();
        dialog.show();
    }
}
Copyright © Linux教程網 All Rights Reserved