Android捕捉视频并使用单个按钮将其上传到服务器 [英] Android capture video and upload it to server using single button

查看:127
本文介绍了Android捕捉视频并使用单个按钮将其上传到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



工作流程:
一个按钮将会被一个按钮被用来上传你自己的视频

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

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

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



我发布了以下源代码:

文件上传的源代码:

  // messageText.setText(上传文件路径: - '/ mnt / sdcard /+ uploadFileName +'); 
$ b $ messageText.setText(上传文件路径: - '/ storage / emulated / 0 /+ uploadFileName +');

/ ************* PHP脚本路径**************** /
upLoadServerUri =MY_SERVER_LINK ;
$ b $ uploadButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){

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

新线程(new Runnable(){
public void run(){
runOnUiThread ()
public void run(){
messageText.setText(upload up started .....);
}
});

uploadFile(uploadFilePath ++ uploadFileName);


})。start();
}
});


public int uploadFile(String sourceFileUri){


String fileName = sourceFileUri;

HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd =\r\\\
;
String twoHyphens = - ;
String boundary =*****;
int bytesRead,bytesAvailable,bufferSize;
byte [] buffer;
int maxBufferSize = 1 * 1024 * 1024;
文件sourceFile =新文件(sourceFileUri);如果(!sourceFile.isFile()){

dialog.dismiss();


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

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

返回0;

}
else
{
try {

//打开一个URL连接到Servlet
FileInputStream fileInputStream = new的FileInputStream(的资源文件);
URL url =新的URL(upLoadServerUri);

//打开一个HTTP连接到URL
conn =(HttpURLConnection)url.openConnection();
conn.setDoInput(true); //允许输入
conn.setDoOutput(true); //允许输出
conn.setUseCaches(false); //不要使用缓存副本
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);

//创建最大大小的缓冲区
bytesAvailable = fileInputStream.available();

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

//读取文件并将其写入表单...
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);



//在文件数据之后发送多部分表单数据必需...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

//服务器响应(代码和消息)
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 =文件上传已完成。\\\
\\\
在此处查看上传的文件:\\\
\\\

+MY_SERVER_LINK
+ uploadFileName;

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

//关闭流//
fileInputStream.close();
dos.flush();
dos.close();
$ b $ catch(MalformedURLException ex){

dialog.dismiss();
ex.printStackTrace();
$ b runOnUiThread(new Runnable(){
public void run(){
messageText.setText(MalformedURLException Exception:check script url。);
Toast。 makeText(MainActivity.this,MalformedURLException,
Toast.LENGTH_SHORT).show();
}
}); (上传文件到服务器,错误:+ ex.getMessage(),前);

Log.e
} catch(Exception e){

dialog.dismiss();
e.printStackTrace();
$ b $ 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(上传文件到服务器异常,例外:
+ e.getMessage(),e);
}
dialog.dismiss();
返回serverResponseCode;

} // End else block

视频捕获的源代码:

  @Override 
保护无效的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(){
$ b $ @Override
public void onClick(View arg0){

/ /创建新的Intentwith标准意图行动,可以
//发送到让相机应用程序捕获视频并返回它
意向意图=新的意图(MediaStore.ACTION_VIDEO_CAPTURE);

//创建一个文件来保存视频
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

//设置图像文件名称
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

//将视频图像质量设置为高
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);

//启动视频捕捉意图
startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

}});

$ b $ **创建文件Uri保存图片或视频* /
private static Uri getOutputMediaFileUri(int type){

return Uri.fromFile(getOutputMediaFile(类型));

$ b $ **创建一个保存图片或视频文件* /
private static File getOutputMediaFile(int type){

//检查SD卡是否挂载
文件mediaStorageDir =新文件(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),MyCameraVideo);


//创建存储目录(MyCameraVideo)如果不存在
if(!mediaStorageDir.exists()){

if !mediaStorageDir.mkdirs()){

output.setText(无法创建目录MyCameraVideo。);

Toast.makeText(ActivityContext,无法创建目录MyCameraVideo。,
Toast.LENGTH_LONG).show();

Log.d(MyCameraVideo,无法创建目录MyCameraVideo。);
返回null;
}
}


//创建一个媒体文件名

//用于追加当前时间戳文件的唯一文件名
java.util.Date date = new java.util.Date();
String timeStamp = new SimpleDateFormat(yyyyMMdd_HHmmss)
.format(date.getTime());

文件mediaFile;

if(type == MEDIA_TYPE_VIDEO){

//对于唯一的视频文件名追加当前timeStamp文件名
mediaFile = new File(mediaStorageDir.getPath( )+ File.separator +
VID _+ timeStamp +.mp4);

} else {
return null;
}

return mediaFile;


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

//相机后(requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE){

if(resultCode == RESULT_OK){

output.setText(Video文件:+ data.getData());

//将视频捕获并保存到在Intent中指定的fileUri
Toast.makeText(this,Video saved to:+
data.getData(),Toast.LENGTH_LONG )。显示();

} else if(resultCode == RESULT_CANCELED){

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

//用户取消了视频截图
Toast.makeText(这个用户取消了视频截图,
Toast.LENGTH_LONG).show();

} else {

output.setText(Video capture failed。);

//视频捕捉失败,建议用户
Toast.makeText(这个视频捕捉失败,
Toast.LENGTH_LONG).show();




$ div class =h2_lin>解决方案

在您的视频捕捉代码中,您称为

$ p $ start $ c $ startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

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

  @覆盖

保护void onActivityResult(int requestCode,final int resultCode,意图数据)
{
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(){
$ b $ @Override
public void run(){
//调用上传的代码


runOnUiThread(new Runnable(){

@Override
public void run(){


dialog.dismiss();
$ b}
});
}
}) 。开始();


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

解决方案

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

这篇关于Android捕捉视频并使用单个按钮将其上传到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆