如何将图像/视频网址传递到android中的另一种方法

时间:2014-12-03 09:18:25

标签: php android

我在尝试将图像r视频捕获到我的localhost服务器后尝试上传视频。这是我的代码。摄像头捕获活动正常并存储在所需目录中,存储的目录路径也存储在另一个变量中。一次我调用上传方法。它显示强制关闭对话框来显示错误日志  java.lang.NoClassDefFoundError:org.apache.http.entity.mime.content.FileBody。

我还添加了所有必要的lib文件。

当我运行个人上传代码时,它会工作gud ..并且文件已上传。

我也从服务器检索。

谢谢你提前

public class MainActivity extends Activity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

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

private Uri fileUri; // file url to store image/video
HttpEntity resEntity;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo,upload;
protected TextView tv1,res;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    videoPreview = (VideoView) findViewById(R.id.videoPreview);
    btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
    btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
    upload = (Button) findViewById(R.id.upload);
    tv1=(TextView) findViewById(R.id.tv1);

    /**
     * Capture image button click event
     */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            captureImage();
        }
    });

    /**
     * Record video button click event
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            recordVideo();
        }
    });

    upload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            upload();
        }
    });

    // 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();
    }
}

/**
 * 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);
}

/**
 * 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");
}

/**
 * Recording video
 */

public void upload()

{
     tv1.setText(String.valueOf((fileUri.getPath()))); 
     String v=String.valueOf((fileUri.getPath()));
     File file1 = new File(v);
     String urlString = "http://192.168.6.170/upload/upload_media_test.php";
     try
     {
          HttpClient client = new DefaultHttpClient();
          HttpPost post = new HttpPost(urlString);
          FileBody bin1 = new FileBody(file1);

          MultipartEntity reqEntity = new MultipartEntity();
          reqEntity.addPart("uploadedfile1", bin1);

          reqEntity.addPart("user", new StringBody("User"));
          post.setEntity(reqEntity);
          HttpResponse response = client.execute(post);
          resEntity = response.getEntity();
          final String response_str = EntityUtils.toString(resEntity);
          if (resEntity != null) {
              Log.i("RESPONSE",response_str);
              runOnUiThread(new Runnable(){
                     public void run() {
                          try 
                          {
                             res.setTextColor(Color.GREEN);
                             res.setText("n Response from server : n " + response_str);
                             Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
                         } catch (Exception e) {
                             e.printStackTrace();
                         }
                        }
                 });
          }
     }
     catch (Exception ex){
          Log.e("Debug", "error: " + ex.getMessage(), ex);
     }


   }

private void recordVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

    // set video quality
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);


    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
                                                        // name
    intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
    // start the video capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);


}

/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // 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
            previewCapturedImage();
            System.out.print(fileUri);
           // tv1.setText(String.valueOf((fileUri.getPath()))); 

        } 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();
        }
    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // video successfully recorded
            // preview the recorded video
            previewVideo();
            System.out.print(fileUri);
          //  tv1.setText(String.valueOf((fileUri.getPath()))); 
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled recording
            Toast.makeText(getApplicationContext(),
                    "User cancelled video recording", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to record video
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

/**
 * Display image from a path to ImageView
 */
private void previewCapturedImage() {
    try {
        // hide video preview
        videoPreview.setVisibility(View.GONE);

        imgPreview.setVisibility(View.VISIBLE);

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        imgPreview.setImageBitmap(bitmap);
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

/**
 * Previewing recorded video
 */
private void previewVideo() {
    try {
        // hide image preview
        imgPreview.setVisibility(View.GONE);

        videoPreview.setVisibility(View.VISIBLE);
        videoPreview.setVideoPath(fileUri.getPath());
        // start playing
        videoPreview.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * ------------ Helper Methods ---------------------- 
 * */

/**
 * 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());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");

    } else {
        return null;
    }

    return mediaFile;
}
}

错误日志:

12-03 15:22:48.664: E/AndroidRuntime(17392): FATAL EXCEPTION: main
12-03 15:22:48.664: E/AndroidRuntime(17392): Process: com.example.newvideo, PID: 17392
12-03 15:22:48.664: E/AndroidRuntime(17392): java.lang.NoClassDefFoundError: org.apache.http.entity.mime.content.FileBody
12-03 15:22:48.664: E/AndroidRuntime(17392):    at com.example.newvideo.MainActivity.upload(MainActivity.java:175)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at com.example.newvideo.MainActivity$3.onClick(MainActivity.java:97)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at android.view.View.performClick(View.java:4630)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at android.view.View$PerformClick.run(View.java:19339)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at android.os.Handler.handleCallback(Handler.java:733)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at android.os.Handler.dispatchMessage(Handler.java:95)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at android.os.Looper.loop(Looper.java:157)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at android.app.ActivityThread.main(ActivityThread.java:5335)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at java.lang.reflect.Method.invokeNative(Native Method)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at java.lang.reflect.Method.invoke(Method.java:515)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
12-03 15:22:48.664: E/AndroidRuntime(17392):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

导入android.os.StrictMode;

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);