android选择视频文件上传到后台服务器
本文实例为大家分享了android选择视频文件上传到后台服务器的具体代码,供大家参考,具体内容如下
选择本地视频文件
附上Demo
首先第一步打开打开相册选择视频文件:
Intentintent=newIntent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
((Activity)ctx).startActivityForResult(intent,
ProfilePhotoTask.PHOTO_CAMERA);
ProfilePhotoTask.PHOTO_CAMERA为请求返回码
第二步处理返回结果:
/**
*视频回调
*/
@Override
publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
switch(requestCode){
caseProfilePhotoTask.PHOTO_CAMERA:
if(resultCode==Activity.RESULT_OK){
try{
Uriuri=data.getData();
uri=BitmapCache.geturi(this,data);
path=getPath(uri);
Filefile=newFile(path);
if(!file.exists()){
break;
}
if(file.length()>100*1024*1024){
commonToast("文件大于100M");
break;
}
//传换文件流,上传
submitVedio();
}catch(Exceptione){
}catch(OutOfMemoryErrore){
}
}
break;
}
}
第三步转换文件为流进行上传:这种把文件全读到内存中,易内存泄露。已经修改为断点续传,参见开篇demo
try{
fInfos=newArrayList();
files=newArrayList();
PhoneUploadFileInfofInfo=newPhoneUploadFileInfo();
fInfo.setFileType(path.substring(path.lastIndexOf(".")+1));
fInfo.setOriginalName(path.substring(path
.lastIndexOf("/")+1));
ByteArrayInputStreamins=FileUtil
.getByteArrayInputStream(newFile(path));
files.add(ins);
//上传文件其他信息
fInfos.add(fInfo);
ins=null;
}catch(Exceptionex){
Stringa=ex+"";
}
视频文件转换为流方法:
publicstaticByteArrayInputStreamgetByteArrayInputStream(Filefile){
returnnewByteArrayInputStream(getByetsFromFile(file));
}
/**
*ByteArrayInputStreamins=newByteArrayInputStream(picBytes);
*@paramfile
*@return
*/
publicstaticbyte[]getByetsFromFile(Filefile){
FileInputStreamis=null;
//获取文件大小
longlength=file.length();
//创建一个数据来保存文件数据
byte[]fileData=newbyte[(int)length];
try{
is=newFileInputStream(file);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
intbytesRead=0;
//读取数据到byte数组中
while(bytesRead!=fileData.length){
try{
bytesRead+=is.read(fileData,bytesRead,fileData.length-bytesRead);
if(is!=null)
is.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
returnfileData;
}
断点续传核心代码:
try{
Filefile=newFile(path);
FileInputStreamis=null;
//获取文件大小
longlength=file.length();
//创建一个数据来保存文件数据
byte[]fileData=null;
try{
is=newFileInputStream(file);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
//读取数据到byte数组中
Listtemp=newArrayList<>();
intlen=0;
fileData=newbyte[1000*1000*2];
//断点续传
while((len=is.read(fileData))!=-1){
temp=newArrayList<>();
ByteArrayInputStreambyteArrayInputStream=newByteArrayInputStream(fileData);
temp.add(byteArrayInputStream);
//这里是提交数组流到后台
//RegisterControlService.submitVedioSon(
//SubVedioViewActivity.this,temp,fInfos,subIdx);
temp.clear();
byteArrayInputStream.close();
}
if(is!=null)
is.close();
}catch(Exceptionex){
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。