Android 使用 HTTP 多部分表单数据将视频上传到远程服务器 [英] Android upload video to remote server using HTTP multipart form data

查看:15
本文介绍了Android 使用 HTTP 多部分表单数据将视频上传到远程服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在当前项目的某个部分遇到了问题,感觉现在被卡住了.我正在尝试使用 HTTP 帖子和多部分表单数据上传视频.我觉得我在理解 HTTP 协议和特别是多部分表单数据方面遇到了困难.

I'm having trouble on a certain piece of a current project and feel like I'm stuck right now. I'm trying to do a video upload with an HTTP post and multipart form data. I feel like I'm hit a wall in understanding the HTTP protocol and specifically multipart form data.

我有一个 URL,可以将视频上传到 http://videoupload.thecompany.com/VideoApp.xml?method=upload&objectType=person&objectId=777777.当然,我还需要包含标题、描述和视频文件.这些是多部分数据"吗?

I have a URL to upload videos to in the format http://videoupload.thecompany.com/VideoApp.xml?method=upload&objectType=person&objectId=777777. I also need to include a title, description, and the videoFile of course. Are these the "multipart data"?

我尝试调整此解决方案以满足我的需求 将视频从 Android 上传到服务器?,并在所有其他 conn.setRequestProperty() 调用之后设置额外数据,如下所示:

I've tried adapting this solution to meet my needs Upload video from Android to server?, and setting the extra data following all the other conn.setRequestProperty() calls like so:

conn.setRequestProperty("title", "video title");
conn.setRequestProperty("description", "video description");

但这对我不起作用.代码的原作者有一个评论,在大约 30 行之后添加多部分表单数据,但我不明白为什么.感谢您的帮助.

But this isn't working for me. There's a comment from the original author of the code to add multipart form data about 30 lines later, but I don't understand why. Thanks for any help.

推荐答案

这是我想出的两步解决方案,主要来自找到的信息和链接 此处.这个解决方案对我来说比一些相关的 SO 帖子中的 upload2server() 方法更容易掌握.希望这对其他人有帮助.

Here's the two step solution I came up with, largely from the information and links found here. This solution was easier for me to grasp than the upload2server() method in some of the related SO posts. Hope this helps someone else.

1) 从图库中选择视频文件.

1) Select the video file from the gallery.

创建一个变量 private static final int SELECT_VIDEO = 3; -- 无论您使用什么数字,只要您稍后检查该数字即可.然后,使用 Intent 选择视频.

Create a variable private static final int SELECT_VIDEO = 3; -- it doesn't matter what number you use, so long as that's to one you check for later on. Then, use an intent to select a video.

Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select a Video "), SELECT_VIDEO);

使用 onActivityResult() 启动 uploadVideo() 方法.

Use onActivityResult() to start the uploadVideo() method.

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {

        if (requestCode == SELECT_VIDEO) {
            System.out.println("SELECT_VIDEO");
            Uri selectedVideoUri = data.getData();
            selectedPath = getPath(selectedVideoUri);
            System.out.println("SELECT_VIDEO Path : " + selectedPath);

            uploadVideo(selectedPath);
        }      
    }
}

private String getPath(Uri uri) {
    String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION}; 
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    cursor.moveToFirst(); 
    String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
    int fileSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
    long duration = TimeUnit.MILLISECONDS.toSeconds(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)));


    //some extra potentially useful data to help with filtering if necessary
    System.out.println("size: " + fileSize);
    System.out.println("path: " + filePath);
    System.out.println("duration: " + duration);

    return filePath;
}

2) 转到 http://hc.apache.org/downloads.cgi,下载最新的HttpClient jar,将其添加到您的项目中,并使用以下方法上传视频:

2) Go to http://hc.apache.org/downloads.cgi, download the latest HttpClient jar, add it to your project, and upload the video using the following method:

private void uploadVideo(String videoPath) throws ParseException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(YOUR_URL);

    FileBody filebodyVideo = new FileBody(new File(videoPath));
    StringBody title = new StringBody("Filename: " + videoPath);
    StringBody description = new StringBody("This is a description of the video");

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("videoFile", filebodyVideo);
    reqEntity.addPart("title", title);
    reqEntity.addPart("description", description);
    httppost.setEntity(reqEntity);

    // DEBUG
    System.out.println( "executing request " + httppost.getRequestLine( ) );
    HttpResponse response = httpclient.execute( httppost );
    HttpEntity resEntity = response.getEntity( );

    // DEBUG
    System.out.println( response.getStatusLine( ) );
    if (resEntity != null) {
      System.out.println( EntityUtils.toString( resEntity ) );
    } // end if

    if (resEntity != null) {
      resEntity.consumeContent( );
    } // end if

    httpclient.getConnectionManager( ).shutdown( );
} // end of uploadVideo( )

一旦你让它工作,你可能想把它放在一个线程中并添加一个上传对话框,但这会让你开始.在我尝试 upload2Server() 方法失败后为我工作.这也适用于经过一些细微调整的图像和音频.

Once you have it working you'll probably want to put it in a thread and add an uploading dialog, but this will get you started. Working for me after I unsuccessfully tried the upload2Server() method. This will also work for images and audio with some minor tweaking.

这篇关于Android 使用 HTTP 多部分表单数据将视频上传到远程服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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