Android如何简易地上传一个视频


继续上一篇文章讲到的图片缩略图,这篇首先讲一下,如何获取本地视频的缩略图。

方法其实很简单,只需要我们将获得的Uri传入方法即可。

private Bitmap getVedioPic(Uri uri) {

MediaMetadataRetriever retriever = new MediaMetadataRetriever();

retriever.setDataSource(getBaseContext(), uri);

Bitmap bmp = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

Bitmap mBitmap = Bitmap.createScaledBitmap(bmp, 200, 200, true);

return mBitmap;}

该方法是获取视频的第一帧,网上还有获取视频最大帧的方法,不作赘述。

接着便是视频上传的方法了。

首先结合retrofit,在@Post上方加入@Multipart,默认以大量文件数据的方法上传,然后,因为我们在请求中可能还需要别的参数,而不是单独一个视频,所以采用Map封装Request来上传,@PartMap Map<String, RequestBody> map,整个请求就一个map参数。

最后便是Map的封装方法,首先要获得视频的Path,这个在上一篇已经提到,采用一样的方法即可。

File file = new File(vedioPath);

Map<String, RequestBody> map = new HashMap<>();

String fileName =GetRandomName().concat(vedioPath.substring(vedioPath.indexOf(".")));

map.put("fileType", parseRequestBody("vedio"));

map.put("fileName", parseRequestBody(fileName));

map.put(parseFileMapKey("file", fileName), parseFileRequestBody(file));

在map中,我们加入了参数fileType,fileName。

最后是将文件包裹起来。

涉及到的方法:

public static RequestBody parseRequestBody(String value) { //普通参数

return RequestBody.create(MediaType.parse("text/plain"), value);

}

public static RequestBody parseFileRequestBody(File file) { //文件参数

return RequestBody.create(MediaType.parse("multipart/form-data"), file);

}

public static String parseFileMapKey(String key, String fileName) { //文件key封装

return key + ""; filename="" + fileName;

}

此处parseFileMapKey由于/上传错误 所以以图片格式上传

将map传入请求即可成功上传视频。