2014-01-21 34 views
1

我正在制作一个应用程序,我必须捕获视频并将其上传到服务器,例如藤蔓应用程序。Android捕获视频并使用单个按钮将其上传到服务器

的工作流程: 一个按钮将用于“上传自己的视频”

当用户点击该按钮就会打开相机,并开始录制视频。当用户停止录制时,视频将保存在SD卡上的文件夹中,并自动上传到服务器。

我有两个测试项目。一个捕捉视频并保存它。其他上传视频或任何文件到服务器上。 关于上传视频项目,我预先分配了一个特定的文件。

我的问题是如何合并这两个项目来完成我的需求。下面

我张贴的源代码:

源代码文件上传:

// 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 

源代码视频拍摄:

@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(); 
     } 
    } 
} 
+0

你是否曾经能够弄清楚这一点? –

回答

0

在您的视频捕捉代码在调用

startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE); 

合并它们,将onActivityResult添加到同一个文件

@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(); 
相关问题