这是我想出的两步解决方案,主要来自此处的信息和链接。这个解决方案对我来说比一些相关 SO 帖子中的 upload2server() 方法更容易掌握。希望这对其他人有帮助。
1) 从图库中选择视频文件。
创建一个变量private static final int SELECT_VIDEO = 3;
——你使用什么数字并不重要,只要那是你以后检查的那个。然后,使用意图来选择视频。
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select a Video "), SELECT_VIDEO);
使用 onActivityResult() 启动 uploadVideo() 方法。
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,将其添加到您的项目中,并使用以下方法上传视频:
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() 方法失败后为我工作。这也适用于图像和音频,只需稍作调整。