Aquí está la solución de dos pasos que se me ocurrió, en gran parte a partir de la información y los enlaces encontrados here. Esta solución fue más fácil de entender que el método upload2server() en algunas de las publicaciones SO relacionadas. Espero que esto ayude a alguien más.
1) Seleccione el archivo de video de la galería.
Crea una variable private static final int SELECT_VIDEO = 3;
- no importa el número que uses, siempre que sea uno que revises más adelante. Luego, usa un intento para seleccionar un video.
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select a Video "), SELECT_VIDEO);
Utilice onActivityResult() para iniciar el método 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) Ir a http://hc.apache.org/downloads.cgi, descargar la última jarra HttpClient, añadirlo a su proyecto, y subir el vídeo usando el siguiente método:
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()
vez que lo tienes que trabajar probablemente quiere ponerlo en un hilo y agregar un diálogo de carga, pero esto lo ayudará a comenzar. Trabajando para mí después de probar infructuosamente el método upload2Server(). Esto también funcionará para imágenes y audio con algunos ajustes menores.
¡Tan bueno! ¿Es esto útil para video de gran tamaño? ¿O puede usarse para otros tipos de archivos? –
@AliBagheriShakib debería funcionar bien para videos más grandes. Sí, puede usarse para clips de audio u otros tipos de archivos de forma muy similar. Hasme saber si tienes algunos problemas. –
Sí @Kyle Clegg. Funcionó perfectamente para mí. Mis problemas resueltos hermano :) Publiqué mi propia experiencia también: http://stackoverflow.com/q/23504191/2624611 –