Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

Android upload video to remote server using HTTP multipart form data

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.

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"?

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) Select the video file from the gallery.

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...