1. 程式人生 > >拍照上傳圖片與從相簿中選擇圖片上傳

拍照上傳圖片與從相簿中選擇圖片上傳

手機拍照與上傳圖片是APP中很常用的功能。
我們先寫個佈局,然後程式碼實現。

MediaStore.ACTION_IMAGE_CAPTURE); //呼叫相機
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);

1佈局
這裡寫圖片描述

 <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <include
            android:id
="@+id/title" layout="@layout/title" />
</RelativeLayout> <LinearLayout style="@style/common_linearlayout" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="vertical" > <ImageView
android:id="@+id/load_ic" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="280dp" android:scaleType="fitCenter" android:src="@drawable/takephoto" />
<FrameLayout android:layout_width
="match_parent" android:layout_height="wrap_content" android:background="#fff" android:paddingBottom="17dp" android:paddingTop="16dp" android:visibility="gone" >
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="示意圖" android:textColor="#fa5655" android:textSize="24sp" android:visibility="gone" /> </RelativeLayout> </FrameLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="25dp" android:layout_marginLeft="15dp" android:layout_marginTop="10dp" android:text="" android:textSize="13sp" /> <Button android:id="@+id/upload" style="@style/common_button_red" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="上傳照片" /> </LinearLayout>

2,拍照

//拍完照後,照片要儲存的路徑。
String tempImg = Environment.getExternalStorageDirectory() + "/appName/"+ "temp.jpg";
    private void findView() {
        context = this;
        mUpload = (Button) findViewById(R.id.upload);
        mloadiv = (ImageView) findViewById(R.id.load_ic);
        //picName 是個照片檔案路徑,判斷這個 mloadiv 這個位置有沒有照片,有的話,直接設定到這。
        if (Util.isEmpty(picName) || picName.equals("")) {
        } else {
            Bitmap bitmap5 = BitmapUtil.getSmallBitmap(picName, true);
            mloadiv.setImageDrawable(new BitmapDrawable(getResources(), bitmap5));
        }
        // 點選按鈕出現dialog,選擇(拍照,從相簿選,取消)
        mUpload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (uptimes >= 8) {
                    MyToast.showToast(context, "您上傳次數過多");
                    return;
                }

                if (dialog == null) {

                    dialog = new AlertDialog.Builder(context).setItems(
                            new String[]{"拍照", "從手機相簿選擇", "取消"},
                            //Dialog 中的監聽器
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    if (which == 0) {
                                        Intent intent = new Intent(
                                                MediaStore.ACTION_IMAGE_CAPTURE);
                                        intent.putExtra(
                                                MediaStore.EXTRA_VIDEO_QUALITY,
                                                1);
                                        File out = new File(tempImg);
                                        Uri uri = Uri.fromFile(out);
                                        // 獲取拍照後未壓縮的原圖片,並儲存在uri路徑中
                                        intent.putExtra(
                                                MediaStore.EXTRA_OUTPUT, uri);
                                        // intentPhote.putExtra(MediaStore.Images.Media.ORIENTATION,
                                        // 180);
                                        startActivityForResult(intent,
                                                Config.requestCode_1);

                                    } else if (which == 1) {
                                        Intent local = new Intent(Intent.ACTION_PICK, null);
                                        local.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                        startActivityForResult(local,
                                                Config.requestCode_4);
                                    } else if (which == 2) {
                                        dialog.dismiss();
                                    }

                                }

                            }).create();

                }

                if (!dialog.isShowing()) {

                    dialog.show();

                }

            }
        });
    }

3,處理圖片

/**
     * 拍照或選擇照片
     */
    @SuppressLint("NewApi")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.requestCode_1) {// 拍照
            if (resultCode == RESULT_OK) {
                DisplayMetrics metric = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels; // 螢幕寬度(畫素)
                int height = metric.heightPixels; // 螢幕高度(畫素)
                Bitmap bitmap1 = BitmapUtil.getSmallBitmap(tempImg, true);// getBitmapFromUrl(tempImg,
                bitmap1 = BitmapUtil.ImageCompressL2(bitmap1);
                if (bitmap1 == null || !saveScalePhoto(bitmap1)) {
                    MyToast.showToast(this, "獲取圖片失敗,請重試");
                    return;
                }
                fileName1 = allurl;
                //將照片設定到上圖的照片iamageView 中
                mloadiv.setImageDrawable(new BitmapDrawable(getResources(),
                        bitmap1));
                PicsUpload();// 開始圖片上傳
            }
        }
        if (requestCode == Config.requestCode_4&&data!=null) {

            Uri uri = data.getData();
            if (null != uri) {
                String StringUri = uri.toString();
                Cursor cursor = null;
                int columnIndex = -1;
                //如果uri有百分號,將百分號轉化為斜線,再進行進一步處理。
                if (StringUri.contains("%")) {
                    try {
                        StringUri = URLDecoder.decode(StringUri, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    //以file開頭的uri,直接擷取獲取路徑
                    if (StringUri.startsWith("file")) {
                        fileName = StringUri.substring(StringUri.indexOf("://") + 4);
                    }

                    //不以file開頭的,即使以content開頭的,uri處理。
                    else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                        // 4.4及以上
                        String[] column = {MediaStore.Images.Media.DATA};
                        cursor = getContentResolver().query(uri, column, null, null, null);
                        columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        if (cursor.moveToFirst()) {
                            fileName = cursor.getString(columnIndex);
                        }
                    } else {
                        // 4.4以下,即4.4以上獲取路徑的方法
                        String[] projection = {MediaStore.Images.Media.DATA};
                        cursor = context.getContentResolver().query(uri,
                                projection, null, null, null);
                        int column_index = cursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        cursor.moveToFirst();
                        fileName = cursor.getString(column_index);
                    }
                    if (fileName != null && !fileName.equals("")) {
                        String name = Util.getTransTime() + ".jpg";
                        String fileDir = Environment.getExternalStorageDirectory()
                                + "/appName/";
                        File file = new File(fileDir);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String picpath = fileDir + name;
                        // 壓縮圖片
                        FileOutputStream out = null;
                        try {
                            Bitmap image = BitmapUtil.getSmallBitmap(fileName, true);
                            if (image == null) {
                                image = BitmapUtil.getSmallBitmap(fileName, 300, 400, true);
                            }
                            //圖片縮放
                            image = BitmapUtil.ImageCompressL(image);
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                            if (image != null && !image.isRecycled()) {
                                image.recycle();
                                image = null;
                                System.gc();
                            }
                            ByteArrayInputStream isBm = new ByteArrayInputStream(
                                    baos.toByteArray());// 把壓縮後的資料baos存放到ByteArrayInputStream中}
                            baos.close();
                            Bitmap bitmap = BitmapFactory
                                    .decodeStream(isBm, null, null);// 把ByteArrayInputStream資料生成圖片
                            out = new FileOutputStream(picpath);// 壓縮完存到此路徑下面
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);// 把ByteArrayInputStream資料生成圖片
                            // 將輸入流複製到輸出流中
                            isBm.close();
                            // 傳給上一頁圖片路徑
                            fileName1 = picpath;
                            mloadiv.setImageDrawable(new BitmapDrawable(getResources(),
                                    bitmap));
                            PicsUpload();// 圖片上傳完成後提交申請
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            fileName = "";
                            MyToast.showToast(context, "獲取圖片失敗,請重試");
                            return;
                        } catch (IOException e) {
                            e.printStackTrace();
                            fileName = "";
                            MyToast.showToast(context, "獲取圖片失敗,請重試");
                            return;
                        } catch (Exception e) {
                            e.printStackTrace();
                            fileName = "";
                            MyToast.showToast(context, "獲取圖片失敗,請重試");
                            return;
                        } catch (OutOfMemoryError err) {
                            fileName = "";
                            MyToast.showToast(context, "獲取圖片失敗,請重試");
                            return;
                        } finally {
                            try {
                                out.flush();
                                out.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (Exception e) {//暫時解決沒有sd卡選擇圖片崩潰的問題
                                // TODO: handle exception
                                e.printStackTrace();
                            }
                        }
                    } else {
//                        MyToast.showToast(context, "請選擇圖片");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
        }
    }

4,上傳圖片

/**
     * 上傳圖片
     */
    private void PicsUpload() {
        mDialog.show();
        //開啟執行緒上傳照片
        new Thread(new Runnable() {

            @Override
            public void run() {
                if (!isFinishing()) {
                    try {
                        dialog.dismiss();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    // TODO Auto-generated method stub
                    if (fileName1 != null) {
//                  int imgid = DownAndUploadPic.uploadImage(flag,fileName1,
//                          mLoginEntity.getSessionId());
                        int imgid = DownAndUploadPic.uploadImage(fileName1);
                        attachmentId = imgid + "";
                        if (Config.isUpPicTo9999) {
                        //上傳到9999網站
                        //返回圖片id
                            attachmentId9999 = DownAndUploadPicTo9999.uploadImage(fileName1);
                            Logout.e("YCW", "attachmentId=" + attachmentId + "\nattachmentId9999=" + attachmentId9999);
                            if (imgid != 0 && !"".equals(attachmentId9999)) {
                                Message message = handler.obtainMessage(0);
                                message.sendToTarget();
                            } else {
                                imgid = 100;
                                Message message = handler.obtainMessage(1);
                                message.sendToTarget();
                            }
                        } else {
                        ////上傳到另一個網站
                            Logout.e("YCW", "attachmentId=" + attachmentId);
                            if (imgid != 0) {
                                Message message = handler.obtainMessage(0);
                                message.sendToTarget();
                            } else {
                                imgid = 100;
                                Message message = handler.obtainMessage(1);
                                message.sendToTarget();
                            }
                        }

                    }
                }
            }
        }).start();
    }

5 上傳成功或者失敗之後怎麼辦

private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if(mDialog.isShowing()){
                mDialog.dismiss();
            }
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    MyToast.showToast(context, "上傳成功");
                    uptimes++;
                    Intent intentPic = new Intent();
                    intentPic.putExtra("picUrl", fileName1);
                    intentPic.putExtra("attachmentId", attachmentId);
                    intentPic.putExtra("attachmentId9999", attachmentId9999);
                    setResult(RESULT_OK, intentPic);
                    finish();
                    break;

                case 1:
                    MyToast.showToast(context, "上傳失敗");
                    break;
            }
        }

    };

7 儲存縮放的圖片

/**
     * 儲存縮放的圖片
     *
     * @param bitmap 圖片資料
     */
    private boolean saveScalePhoto(Bitmap bitmap) {
        // 照片全路徑
        String fileName = "";
        // 資料夾路徑
        String pathUrl = Environment.getExternalStorageDirectory() + "/appName/";
        String imageName = Util.getTransTime() + ".jpg";
        FileOutputStream fos = null;
        File file = new File(pathUrl);
        file.mkdirs();// 建立資料夾
        fileName = pathUrl + imageName;
        try {
            fos = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            allurl = fileName;
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError err) {

        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

8 Bitmap工具類

public class BitmapUtil {

    public static Bitmap getSmallBitmap(String filePath, boolean isNeedRotate) {
        return getSmallBitmap(filePath, 768, 1024, isNeedRotate);
    }

    public static Bitmap getSmallBitmap(String filePath, int width, int height,
            boolean isNeedRotate) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, width, height);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(filePath, options);
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        } catch (OutOfMemoryError ex) {
            try {
                options.inSampleSize = options.inSampleSize * 2;
                bitmap = BitmapFactory.decodeFile(filePath, options);
            } catch (Exception e1) {
                e1.printStackTrace();
                return null;
            } catch (OutOfMemoryError ex1) {
            }
        }
        if (isNeedRotate) {
            int rotate = 0;
            try {
                ExifInterface mExifInterface = new ExifInterface(filePath);
                int result = mExifInterface.getAttributeInt(
                        ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);

                switch (result) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    rotate = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    rotate = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    rotate = 270;
                    break;
                default:
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (OutOfMemoryError ex) {
            }
            if (rotate != 0 && bitmap != null) {
                Matrix m = new Matrix();
                m.setRotate(rotate, (float) bitmap.getWidth() / 2,
                        (float) bitmap.getHeight() / 2);
                try {
                    Bitmap tempBmp = Bitmap.createBitmap(bitmap, 0, 0,
                            bitmap.getWidth(), bitmap.getHeight(), m, true);
                    // bmp.recycle();
                    bitmap = tempBmp;
                } catch (OutOfMemoryError ex) {
                }
            }
        }
        return bitmap;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
        return output;
    }
    //圖片縮放位64k
    public static Bitmap ImageCompressL(Bitmap bitmap) {
        double targetwidth = Math.sqrt(64.00 * 1000);
        if (bitmap.getWidth() > targetwidth || bitmap.getHeight() > targetwidth) {
            // 建立操作圖片用的matrix物件
            Matrix matrix = new Matrix();
            // 計算寬高縮放率
            double x = Math.max(targetwidth / bitmap.getWidth(), targetwidth
                    / bitmap.getHeight());
            // 縮放圖片動作
            matrix.postScale((float) x, (float) x);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);
        }
        return bitmap;
    }
    //圖片縮放位100k
    public static Bitmap ImageCompressL2(Bitmap bitmap) {
        double targetwidth = Math.sqrt(900.00 * 1000);
        if (bitmap.getWidth() > targetwidth || bitmap.getHeight() > targetwidth) {
            // 建立操作圖片用的matrix物件
            Matrix matrix = new Matrix();
            // 計算寬高縮放率
            double x = Math.max(targetwidth / bitmap.getWidth(), targetwidth
                    / bitmap.getHeight());
            // 縮放圖片動作
            matrix.postScale((float) x, (float) x);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);
        }
        return bitmap;
    }

}

9 圖片上傳下載的工具類 (1)

public class DownAndUploadPic {
    /**
     * 模擬表單上傳圖片
     *
     * @param filePath
     *            圖片本地地址
     * @return
     */
    public static int uploadImage(String filePath) {
        int attachmentId = 0;
        HttpURLConnection conn = null;
        OutputStream out = null;
        DataInputStream in = null;
        Reader inputReader = null;// 結果流
        BufferedReader reader = null;
        URL url = null;
        String BOUNDARY = "---------------------------123456789987456321"; // request頭和上傳檔案內容的分隔符
        try {
            url= new URL(getUpAndDownloadImageUrl()+"upload.do");
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(50000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);

            out = new DataOutputStream(conn.getOutputStream());

            if (filePath != null) {
                File file = new File(filePath);
                String filename = file.getName();
                String contentType = "application/octet-stream";

                if (filename.endsWith(".jpg")) {
                    contentType = "image/jpeg";
                }
                if (contentType == null || contentType.equals("")) {
                    contentType = "application/octet-stream";
                }

                StringBuffer strBuf = new StringBuffer();

                strBuf.append("\r\n").append("--").append(BOUNDARY)
                        .append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\""
                        + "file" + "\"; filename=\"" + filename + "\"\r\n");// file引數名(與後臺對應)
                // filename:檔名稱
                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");// "image/jpeg"
//              Log.e("YCW", "File =" + strBuf);
                System.out.println("File =" + strBuf);
                out.write(strBuf.toString().getBytes());
                in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
//              out.flush();
            }
            if (Constants.downupPicWithSession) {// 有session的上傳
                byte[] endData = ("\r\n--" + BOUNDARY + "\r\n").getBytes();
                out.write(endData);
                StringBuffer strBuf_se = new StringBuffer();
                strBuf_se.append("--").append(BOUNDARY).append("\r\n");
                strBuf_se
                        .append("Content-Disposition: form-data; name=\""
                                + "sessionId" + "\"\r\n\r\n"
                                + Constants.sessionId + "");// session
                strBuf_se.append("\r\n--" + BOUNDARY + "--\r\n");
                Log.e("AAA", "sessionId =" + strBuf_se.toString());
                out.write(strBuf_se.toString().getBytes());
                Log.e("AAA", "out =" + out.toString());

            } else {
                byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
                out.write(endData);
            }

            out.flush();
//          out.close();
            StringBuffer strBuf = new StringBuffer();
            inputReader = new InputStreamReader(conn.getInputStream());
            reader = new BufferedReader(inputReader);
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line);// .append("\n")
                System.out.println("strBuf===" + strBuf);
            }
            String res = strBuf.toString();
            try {
                attachmentId = Integer.parseInt(res);
            } catch (Exception e) {
                Logout.e("AAA", "parse int Failure  " + e.getMessage());
                attachmentId = 0;
            }
            reader.close();
            reader = null;

        } catch (Exception e) {
            Logout.e("AAA", "parse int Failure  " + e.getMessage());
            attachmentId = 0;
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }

                if (in != null) {
                    in.close();
                    in = null;
                }
                if (inputReader != null) {
                    inputReader.close();
                    inputReader = null;
                }
                if (reader != null) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return attachmentId;
    }
}   

9,圖片上傳下載工具類(2)

/**
 *
 * 圖片上傳下載工具類
 * 上傳圖片至9999網站
 *
 * 
 */
public class DownAndUploadPicTo9999 {
    /**
     * 模擬表單上傳圖片
     *
     * @param filePath
     *            圖片本地地址
     * @return
     */
    public static String uploadImage(String filePath) {
        int attachmentId = 0;
        String attachmentIdStr = "";
        HttpURLConnection conn = null;
//      OutputStream out = null;
        PrintWriter out = null;
        DataInputStream in = null;
        Reader inputReader = null;// 結果流
        BufferedReader reader = null;
        URL url = null;
        String BOUNDARY = "---------------------------1234567899988745"; // request頭和上傳檔案內容的分隔符
        try {
            int proid = ActivitySwitch.getInstance().dbProCode;
            String proid_str = Integer.toString(proid);
            String serviceIP = "";
            String servicePort = "";
            if (Config.formal_environment){
                //9999正式環境
                serviceIP = "**.**.**.**";
                servicePort = "8014";
            }else {
                //9999測試環境
            serviceIP = "**.**.**.**";
                servicePort = "8015";

            }
            url = new URL("http://"+serviceIP+":"+servicePort+"/CSUPS/9999/apps/appFileUpload");
            Logout.e("AAA",url.getAuthority()+url.getPath());




            String codeId = ActivitySwitch.company.getCodeId();
            /**對部分內容ca加密**/
            String req = ""+""+codeId+"13"+"9999";
            StringBuffer encryptResult=new StringBuffer(CAHelper.getInstance().loginEncrypt(MyApplication.getInstance(), req));
            String encryStr=encryptResult.subSequence(0, encryptResult.lastIndexOf("|")+1).toString();
            encryStr = "09999"+URLEncoder.encode(encryStr,"utf-8");

            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(50000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");

            //imgFile 圖片的二進位制
            //http://www.cnblogs.com/mailingfeng/archive/2012/01/09/2317100.html
            File file = new File(filePath);
            InputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            for (int len = inputStream.read(temp); len !=-1; len=inputStream.read(temp)) {
                outputStream.write(temp,0,len);
            }
            try {
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                // TODO: handle exception
            }
            String _64PicData = "";
            _64PicData = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
            _64PicData = URLEncoder.encode(_64PicData,"utf-8");

            StringBuffer buffer = new StringBuffer();
            out = new PrintWriter(conn.getOutputStream());
            String target = "11102";
            String srvMode = "13";
            String fileType = ".jpg";

            String sign = "加密串";
            String imgFile = "加密串"+
                    "加密串";
            String param = 入參;
            buffer.append(param);
            out.print(buffer.toString());
            out.flush();
            out.close();

            // 讀取返回資料
            StringBuffer strBuf = new StringBuffer();
            Logout.e("AAA", "連線網路");
            inputReader = new InputStreamReader(conn.getInputStream());
            Logout.e("AAA", "連線網路完畢");
            reader = new BufferedReader(inputReader);
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line);// .append("\n")
                System.out.println("strBuf===" + strBuf);
            }
            Logout.e("AAA", "寫資料完畢");
            String res = strBuf.toString();
            Logout.e("AAA", "網站返回的資料:"+res);
            try {
                if (res!=null&&!res.equals("")) {
                    res = res.replace("\\", "");
                    if (res.startsWith("\"")) {
                        res = res.substring(1);
                    }
                    if (res.endsWith("\"")) {
                        res = res.substring(0,res.length()-1);
                    }
                    Logout.e("AAA", "處理後的資料:"+res);

                    JSONTokener toker = new JSONTokener(res);
                    JSONObject object = (JSONObject) toker.nextValue();
                    String picId = object.getString("webPhotoId");
//                  attachmentId = Integer.parseInt(picId);
                    attachmentIdStr = picId;
                }else {
                    attachmentId = 0;
                    attachmentIdStr = "";
                }

            } catch (Exception e) {
                Log.e("msg", "parse int Failure  " + e.getMessage());
                attachmentId = 0;
                attachmentIdStr = "";
            }
            reader.close();
            reader = null;

        } catch (Exception e) {
            Log.e("msg", " " + e.getMessage());
            attachmentId = 0;
            attachmentIdStr = "";
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }

                if (in != null) {
                    in.close();
                    in = null;
                }
                if (inputReader != null) {
                    inputReader.close();
                    inputReader = null;
                }
                if (reader != null) {
                    reader.close();
                    reader = null