Android capture video and upload it to server using single button

无人久伴 提交于 2019-12-11 07:24:58

问题


I am making an application where i have to capture video and upload it to server like vine application.

Flow of the work: One button will be used "Upload your own video"

When user clicks on the button it will open camera and will start recording video. when user stops recording the video will save on a folder on sdcard and and automatically upload to server.

I have two test project. One capturing video and saving it. Other uploads video or any file onto server. On upload video project i have pre-assign a particular file.

My question is how to merge these two projects to accomplish my needs.

I am posting source code below:

Source code for file upload:

 //   messageText.setText("Uploading file path :- '/mnt/sdcard/"+uploadFileName+"'");

    messageText.setText("Uploading file path :- '/storage/emulated/0/"+uploadFileName+"'");

    /************* Php script path ****************/
    upLoadServerUri = "MY_SERVER_LINK";

    uploadButton.setOnClickListener(new OnClickListener() {            
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);

            new Thread(new Runnable() {
                    public void run() {
                         runOnUiThread(new Runnable() {
                                public void run() {
                                    messageText.setText("uploading started.....");
                                }
                            });                      

                         uploadFile(uploadFilePath + "" + uploadFileName);

                    }
                  }).start();        
            }
        });
}

public int uploadFile(String sourceFileUri) {


  String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;  
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024; 
    File sourceFile = new File(sourceFileUri); 

    if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"
                               +uploadFilePath + "" + uploadFileName);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           +uploadFilePath + "" + uploadFileName);
               }
           }); 

           return 0;

    }
    else
    {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);

               // Open a HTTP  connection to  the URL
               conn = (HttpURLConnection) url.openConnection(); 
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs
               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("uploaded_file", fileName); 

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

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                         + fileName + "\"" + lineEnd);

               dos.writeBytes(lineEnd);

               // create a buffer of  maximum size
               bytesAvailable = fileInputStream.available(); 

               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];

               // read file and write it into form...
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

               while (bytesRead > 0) {

                 dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                }

               // send multipart form data necesssary after file data...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

               // Responses from the server (code and message)
               serverResponseCode = conn.getResponseCode();
               String serverResponseMessage = conn.getResponseMessage();

               Log.v("uploadFile", "HTTP Response is : " 
                       + serverResponseMessage + ": " + serverResponseCode);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {

                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                          +" MY_SERVER_LINK"
                                          +uploadFileName;

                            messageText.setText(msg);
                            Toast.makeText(MainActivity.this, "File Upload Complete.", 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          } catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(MainActivity.this, "MalformedURLException", 
                                                        Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(MainActivity.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : " 
                                               + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

     } // End else block 

Source code for video capture:

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

    ActivityContext = this;

    Button buttonRecording = (Button)findViewById(R.id.recording);
    output = (TextView)findViewById(R.id.output);

    buttonRecording.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {

            // create new Intentwith with Standard Intent action that can be
            // sent to have the camera application capture an video and return it. 
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

            // create a file to save the video
            fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); 

            // set the image file name  
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  

            // set the video image quality to high
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); 

            // start the Video Capture Intent
            startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

        }});
}

/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){

      return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){

    // Check that the SDCard is mounted
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_PICTURES), "MyCameraVideo");


    // Create the storage directory(MyCameraVideo) if it does not exist
    if (! mediaStorageDir.exists()){

        if (! mediaStorageDir.mkdirs()){

            output.setText("Failed to create directory MyCameraVideo.");

            Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.", 
                    Toast.LENGTH_LONG).show();

            Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
            return null;
        }
    }


    // Create a media file name

    // For unique file name appending current timeStamp with file name
    java.util.Date date= new java.util.Date();
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                         .format(date.getTime());

    File mediaFile;

    if(type == MEDIA_TYPE_VIDEO) {

        // For unique video file name appending current timeStamp with file name
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
        "VID_"+ timeStamp + ".mp4");

    } else {
        return null;
    }

    return mediaFile;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // After camera screen this code will excuted

    if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {

        if (resultCode == RESULT_OK) {

            output.setText("Video File : " +data.getData());

            // Video captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Video saved to:" +
                     data.getData(), Toast.LENGTH_LONG).show();

        } else if (resultCode == RESULT_CANCELED) {

            output.setText("User cancelled the video capture.");

            // User cancelled the video capture
            Toast.makeText(this, "User cancelled the video capture.", 
                    Toast.LENGTH_LONG).show();

        } else {

            output.setText("Video capture failed.");

            // Video capture failed, advise user
            Toast.makeText(this, "Video capture failed.", 
                    Toast.LENGTH_LONG).show();
        }
    }
}

回答1:


In your code for video capture you have called

 startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

Merging them, add onActivityResult to the same file

  @Override

    protected void onActivityResult(int requestCode, final int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
      dialog =ProgressDialog.show(Activity.this, "", "loading...",false,true);
       if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
       //call code in upload


   runOnUiThread(new Runnable() {

                                @Override
                                public void run() {


                                    dialog.dismiss();

                                }
                            });
                            }
       }).start();



回答2:


Just copy the code from 1st project into 2nd project to upload your video or any file on server and pass the uri as of your file to uploading function thats it. Also you can use retrofit 2 or looj to upload your file on server.



来源:https://stackoverflow.com/questions/21259799/android-capture-video-and-upload-it-to-server-using-single-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!