2015-05-13 2 views
0

Я многие пытаюсь загрузить изображение в андроиде PHP, но некоторый ответ нулевая проблема ...изображения Загрузка Android Php Response является Null Изображения не uploded

Изображения загрузки андроида ответа является недействительным ... плзло предусмотрен любое идея решить загрузки изображения ....

сторона PHP код совершенно uploded изображение успешно, но андроид сторона не работает этот код ...

MainActivity.java

public class MainActivity extends Activity implements OnClickListener{ 

    // Activity request codes 
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100; 
    private static final int SELECT_PICTURE = 1; 
    public static final int MEDIA_TYPE_IMAGE = 1; 
    JSONObject json = new JSONObject(); 

    // directory name to store captured images and videos 
    private static final String IMAGE_DIRECTORY_NAME = "Hello Camera"; 

    private Uri fileUri; // file url to store image/video 

    private ImageView imgPreview; 
    private Button btnCapturePicture, btn_upload_image; 
    static File mediaFile; 
    Bitmap rotatedBMP=null; 
    String selectedImagePath, 
      ServerUploadPath = "http://192.168.43.195/uploadservices/Images/" 
        + "", str_response; 
    String TAG = "Final Image"; 

    @SuppressLint("NewApi") 
    @TargetApi(Build.VERSION_CODES.GINGERBREAD) 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     if (android.os.Build.VERSION.SDK_INT > 9) { 
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
        .permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 

      setid(); 
      setevent(); 



     } 

//  // Checking camera availability 
     if (!isDeviceSupportCamera()) { 
      Toast.makeText(getApplicationContext(), 
        "Sorry! Your device doesn't support camera", 
        Toast.LENGTH_LONG).show(); 
      // will close the app if the device does't have camera 
      finish(); 
     } 
    } 

private void setevent() { 
     // TODO Auto-generated method stub 
     btnCapturePicture.setOnClickListener(this); 
     btn_upload_image.setOnClickListener(this); 
    } 

    private void setid() { 
     // TODO Auto-generated method stub 
     imgPreview = (ImageView) findViewById(R.id.imageView); 
     btnCapturePicture = (Button) findViewById(R.id.btn_select); 
     btn_upload_image = (Button) findViewById(R.id.btn_upload); 

    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     switch (v.getId()) { 
      case R.id.btn_select: 
       // capture picture 
       CameraAndGallaryCapture(); 

       break; 
      case R.id.btn_upload: 
       /*StaticData.staimage = rotatedBMP; 
       Intent catintent=new Intent(getApplicationContext(),Catagories.class); 
       startActivity(catintent);*/ 
       new UploadTask().execute(rotatedBMP); 

      default: 
       break; 
     } 
    } 





    private void CameraAndGallaryCapture() { 
     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")) { 
        captureImage(); 
       } else if (options[item].equals("Choose from Gallery")) { 
        takePhotoGallery(); 
       } else if (options[item].equals("Cancel")) { 
        dialog.dismiss(); 
       } 
      } 

     }); 
     builder.show(); 
    } 

    private void takePhotoGallery() { 
     Intent intent = new Intent(); 
     intent.setType("image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(intent, "Select Picture"), 
       SELECT_PICTURE); 
    } 

    /** 
    * Checking device has camera hardware or not 
    * */ 
    private boolean isDeviceSupportCamera() { 
     if (getApplicationContext().getPackageManager().hasSystemFeature(
       PackageManager.FEATURE_CAMERA)) { 
      // this device has a camera 
      return true; 
     } else { 
      // no camera on this device 
      return false; 
     } 
    } 

    /* 
    * Capturing Camera Image will lauch camera app requrest image capture 
    */ 
    private void captureImage() { 
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

     fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); 

     intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 

     // start the image capture Intent 
     startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); 
    } 

    /* 
    * Creating file uri to store image/video 
    */ 
    public Uri getOutputMediaFileUri(int type) { 
     return Uri.fromFile(getOutputMediaFile(type)); 
    } 

    /* 
    * returning image/video 
    */ 
    private static File getOutputMediaFile(int type) { 

     // External sdcard location 
     File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), 
       IMAGE_DIRECTORY_NAME); 

     // Create the storage directory if it does not exist 
     if (!mediaStorageDir.exists()) { 
      if (!mediaStorageDir.mkdirs()) { 
       Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " 
         + IMAGE_DIRECTORY_NAME + " directory"); 
       return null; 
      } 
     } 

     // Create a media file name 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", 
       Locale.getDefault()).format(new Date()); 

     if (type == MEDIA_TYPE_IMAGE) { 
      mediaFile = new File(mediaStorageDir.getPath() + File.separator 
        + "IMG_" + timeStamp + ".jpg"); 
     } else { 
      return null; 
     } 
     Log.e("path", "media file:-" + mediaFile); 
     return mediaFile; 
    } 

    /* 
    * Here we store the file url as it will be null after returning from camera 
    * app 
    */ 
    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 

     // save file url in bundle as it will be null on scren orientation 
     // changes 
     outState.putParcelable("file_uri", fileUri); 
    } 

    @Override 
    protected void onRestoreInstanceState(Bundle savedInstanceState) { 
     super.onRestoreInstanceState(savedInstanceState); 

     // get the file url 
     fileUri = savedInstanceState.getParcelable("file_uri"); 
    } 

    /** 
    * Receiving activity result method will be called after closing the camera 
    * */ 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (resultCode == RESULT_OK) { 

      if (requestCode == SELECT_PICTURE) { 
       Uri selectedImageUri = data.getData(); 
       selectedImagePath = getPath(selectedImageUri); 
       System.out.println("Image Path : " + selectedImagePath); 
       Log.d("select pah", "path" + selectedImagePath); 
       previewCapturedImage(); 
      } 

     } 
     // if the result is capturing Image 
     if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) { 
      if (resultCode == RESULT_OK) { 
       // successfully captured the image 
       // display it in image view 
       selectedImagePath = mediaFile.toString(); 
       previewCapturedImage(); 
      } else if (resultCode == RESULT_CANCELED) { 
       // user cancelled Image capture 
       Toast.makeText(getApplicationContext(), 
         "User cancelled image capture", Toast.LENGTH_SHORT) 
         .show(); 
      } else { 
       // failed to capture image 
       Toast.makeText(getApplicationContext(), 
         "Sorry! Failed to capture image", Toast.LENGTH_SHORT) 
         .show(); 
      } 
     } 

    } 

    public String getPath(Uri uri) { 
     String[] projection = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = managedQuery(uri, projection, null, null, null); 
     int column_index = cursor 
       .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 

    /* 
    * Display image from a path to ImageView 
    */ 
    private void previewCapturedImage() { 
     try { 

      int targetW = 380; 
      int targetH = 800; 
      Log.d("Get w", "width" + targetW); 
      Log.d("Get H", "height" + targetH); 
      // Get the dimensions of the bitmap 
      BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
      bmOptions.inJustDecodeBounds = true; 
      BitmapFactory.decodeFile(selectedImagePath, bmOptions); 
      int photoW = bmOptions.outWidth; 
      int photoH = bmOptions.outHeight; 

      // Determine how much to scale down the image 
      int scaleFactor = Math.min(photoW/targetW, photoH/targetH); 

      // Decode the image file into a Bitmap sized to fill the View 
      bmOptions.inJustDecodeBounds = false; 
      bmOptions.inSampleSize = scaleFactor << 1; 
      bmOptions.inPurgeable = true; 
      Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath, 
        bmOptions); 

      Matrix mtx = new Matrix(); 

      try { 

       File imageFile = new File(selectedImagePath); 

       ExifInterface exif = new ExifInterface(
         imageFile.getAbsolutePath()); 
       int orientation = exif.getAttributeInt(
         ExifInterface.TAG_ORIENTATION, 
         ExifInterface.ORIENTATION_NORMAL); 
       Log.e("Orintation", " :-" + orientation); 
       switch (orientation) { 
        case ExifInterface.ORIENTATION_ROTATE_270: 

         mtx.postRotate(270); 
         rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, 
           bitmap.getWidth(), bitmap.getHeight(), mtx, true); 
         if (rotatedBMP != bitmap) 
          bitmap.recycle(); 
         imgPreview.setImageBitmap(rotatedBMP); 

         break; 
        case ExifInterface.ORIENTATION_ROTATE_180: 

         mtx.postRotate(180); 
         rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, 
           bitmap.getWidth(), bitmap.getHeight(), mtx, true); 
         if (rotatedBMP != bitmap) 
          bitmap.recycle(); 
         imgPreview.setImageBitmap(rotatedBMP); 
         break; 
        case ExifInterface.ORIENTATION_ROTATE_90: 

         mtx.postRotate(90); 
         rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, 
           bitmap.getWidth(), bitmap.getHeight(), mtx, true); 
         if (rotatedBMP != bitmap) 
          bitmap.recycle(); 
         imgPreview.setImageBitmap(rotatedBMP); 
         break; 
        case ExifInterface.ORIENTATION_NORMAL: 

         mtx.postRotate(0); 
         rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, 
           bitmap.getWidth(), bitmap.getHeight(), mtx, true); 
         if (rotatedBMP != bitmap) 
          bitmap.recycle(); 
         imgPreview.setImageBitmap(rotatedBMP); 
         break; 
        default: 
         mtx.postRotate(0); 
         rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, 
           bitmap.getWidth(), bitmap.getHeight(), mtx, true); 
         if (rotatedBMP != bitmap) 
          bitmap.recycle(); 
         imgPreview.setImageBitmap(rotatedBMP); 
         // img_profilepic.setImageBitmap(BitmapFactory 
         // .decodeFile(mCurrentPhotoPath)); 

       } 

       Log.i("RotateImage", "Exit orientation: " + orientation); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 
    } 



private class UploadTask extends AsyncTask<Bitmap, Void, Void> { 
     private ProgressDialog Dialog = new ProgressDialog(MainActivity.this); 

     protected void onPreExecute() { 
      Dialog.setMessage("Uploading Image..."); 
      Dialog.setCancelable(false); 
      Dialog.show(); 
     } 

     protected Void doInBackground(Bitmap... bitmaps) { 
      if (bitmaps[0] == null) 
       return null; 
      setProgress(0); 

      Bitmap bitmap = bitmaps[0]; 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert 
      // Bitmap 
      // to 
      // ByteArrayOutputStream 
      // Bitmap 
      // to 
      // ByteArrayOutputStream 
      InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert 
      // ByteArrayOutputStream 
      // to 
      // ByteArrayInputStream 

      DefaultHttpClient httpclient = new DefaultHttpClient(); 
      try { 
       HttpPost httppost = new HttpPost(
         "http://192.168.43.195/uploadservices/upload.php"); 
       // // server 
       HttpClient client = new DefaultHttpClient(); 
       HttpPost httppost1 = new HttpPost(ServerUploadPath); // server 

       MultipartEntity reqEntity = new MultipartEntity(); 
       //reqEntity.addPart("email", "[email protected]"); 
       reqEntity.addPart("uploaded_file", System.currentTimeMillis() 
         + ".jpg", in); 

       httppost1.setEntity(reqEntity); 

       Log.i(TAG, "request " + httppost1.getRequestLine()); 
       HttpResponse response = null; 
       try { 
        response = httpclient.execute(httppost1); 
        str_response = EntityUtils.toString(response.getEntity()); 
       } catch (ClientProtocolException e) { 

        e.printStackTrace(); 
       } catch (IOException e) { 

        e.printStackTrace(); 
       } 
       try { 

        if (response != null) 
         Log.d(TAG, "response " 
           + response.getStatusLine().toString()); 

       } finally { 

       } 
      } finally { 

      } 

      if (in != null) { 
       try { 
        in.close(); 
       } catch (IOException e) { 

        e.printStackTrace(); 
       } 
      } 

      if (stream != null) { 
       try { 
        stream.close(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 

      return null; 
     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
      // TODO Auto-generated method stub 
      super.onProgressUpdate(values); 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 
      Dialog.dismiss(); 
      Log.e("Response is", "..." + str_response); 

      Toast.makeText(getApplicationContext(), "Upload Complete....", 
        Toast.LENGTH_LONG).show(); 

     } 
    } 


} 

*** PHP код:

upload.php ***

<?php 


    $image_name = $_FILES["uploaded_file"]["name"]; 
    $tmp_arr = explode(".",$image_name); 
    $img_extn = end($tmp_arr); 
    $new_image_name = 'image_'. uniqid() .'.'.$img_extn;  
    $flag=0;     
    if (file_exists("Images/".$new_image_name)) 
    { 
     $dataObj->ResponseMessage("2","already exists.","False"); 
    } 
    else 
    { 

     move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name); 
     $flag = 1; 
     $static_url = "http://http://192.168.1.103/ppp/sharechat/Images/".$new_image_name; 

     echo "file insert "; 

    } 
    ?> 

ответ

0

Это поможет вам

public class PhotoUploader extends AsyncTask<String, Void, String> { 


     private String photoNameInServer; 
     private static final int PHOTO_QUALITY = 70; 
     private Photo photoToBeUploaded; 

     @Override 
     protected String doInBackground(String... params) { 


       //Uploading Image 
       Bitmap bmp = BitmapFactory.decodeFile(params[0]); //ImagePath 

       //Hey Client, I want to post few photos, Let's bring it. 
       HttpClient client = new DefaultHttpClient(); 
       HttpContext context = new BasicHttpContext(); 

       //Passing data in POST 
       HttpPost post = new HttpPost("http://example.com/post.php"); //URL 

       //This is multipart data (file) 
       MultipartEntity entity = new MultipartEntity(); 
       ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
       bmp.compress(Bitmap.CompressFormat.JPEG, PHOTO_QUALITY, bos); 
       byte[] data = bos.toByteArray(); 

       entity.addPart("photo", new ByteArrayBody(data, "image/jpeg", photoNameInServer)); 
       post.setEntity(entity); 

       try { 
        HttpResponse response = client.execute(post, context); 

        finalResponse = EntityUtils.toString(response.getEntity()); 

        Log.d("X", "Final Response:" + finalResponse); 

       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 


      return finalResponse; 
     } 

     @Override 
     protected void onPostExecute(String result) { 

     } 
    } 

, то вы можете загрузить изображение на

new PhotoUploader().execute("file-path"); 

и не получите, чтобы добавить библиотеку httpmime-4.1.3.

+0

# Спасибо, что это работает ... –

+0

@PrAfulPArmar 10months !! : D – theapache64

+0

Извините bro.i попробует этот код до 10 месяцев его работы. Но я открою счет сегодня ... thanksss –

Смежные вопросы