首先,明白阿里云OSS是个什么鬼

阿里云对象存储(Object Storage 
Service,简称OSS),是阿里云对外提供的海量,安全,低成本,高可靠的云存储服务。用户可以通过调用API,在任何应用、任何时间、任何地点上传和下载数据,也可以通过用户Web控制台对数据进行简单的管理。OSS适合存放任意文件类型,适合各种网站、开发企业及开发者使用。

以上是官方解释。可以看出,OSS可以为我们在后台保存任何数据,强大无比。

步入正题: 
首先你得有个阿里云账号(淘宝账号也可以哦,毕竟阿里账号都通用),然后登陆后进入管理控制台,并点击进去选择对象存储OSS,点击立即开通。 
 

点击立即开通。认证过后,提示开通成功,然后进入OSS控制台。 


到这里它会提示我们新建一个bucket,bucket就相当于我们的总仓库名称。填写名字,选择离自己所在地最近的区域,选择读写权限。 
 
 

可以看到我们的bucket已经创建成功,下来点击object管理,进去之后,我们就可以上传文件了。 


点击上传文件,上传成功后并刷新就可以看到我们的文件乖乖的呆在bucket里了。点击后面的获取地址就可以得到这个文件的(下载)访问路径了。 

最后在上边我们可以看到一个accesskeys,点击进去,创建自己的accesskey,注意一定要保密好,“钥匙”只能你自己有!!!!

最后一步,将我们需要的jar包和sdk导入lib中。下面给出下载链接: 
http://download.csdn.net/detail/u012534831/9501552

开始入手使用: 
 
两个activity,两个xml。 
第一个Mainactivity中,点击选择视频,并填写文件名(也就是object名),选择后点击上传,上传完成提示uploadsuccess,可以在OSS后台看到这个资源。再点击网络播放按钮,从后台下载这个视频并播放,同时实现了缓存到本地。

public class MainActivity extends ActionBarActivity {private TextView tv,detail;private Button camerabutton,playbutton,selectvideo;private ProgressBar pb;private String path,objectname;private EditText filename;private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findbyid();}private void findbyid() {// TODO Auto-generated method stubselectvideo= (Button) findViewById(R.id.camerabutton);detail= (TextView) findViewById(R.id.detail);tv = (TextView) findViewById(R.id.text);pb = (ProgressBar) findViewById(R.id.progressBar1);camerabutton = (Button) findViewById(R.id.camerabutton);playbutton= (Button) findViewById(R.id.playbutton);filename=(EditText) findViewById(R.id.filename);playbutton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent(MainActivity.this, PlayVideoActivity.class);//传过去一个object名intent.putExtra("objectname", objectname);//设置缓存目录intent.putExtra("cache",Environment.getExternalStorageDirectory().getAbsolutePath()+ "/VideoCache/" + System.currentTimeMillis() + ".mp4");startActivity(intent);}});//上传按钮camerabutton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {beginupload();}});}//从图库选择视频public void selectvideo(View view){//跳到图库Intent intent = new Intent(Intent.ACTION_PICK);//选择的格式为视频,图库中就只显示视频(如果图片上传的话可以改为image/*,图库就只显示图片)intent.setType("video/*");// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERYstartActivityForResult(intent, PHOTO_REQUEST_GALLERY);}
//    /*
//          * 判断sdcard是否被挂载
//          */
//         private boolean hasSdcard() {//             if (Environment.getExternalStorageState().equals(
//                     Environment.MEDIA_MOUNTED)) {//                 return true;
//            } else {//                 return false;
//             }
//         }public void beginupload(){//通过填写文件名形成objectname,通过这个名字指定上传和下载的文件objectname=filename.getText().toString();if(objectname==null||objectname.equals("")){Toast.makeText(MainActivity.this, "文件名不能为空", 2000).show();return;}//填写自己的OSS外网域名String endpoint = "http://oss-cn-shanghai.aliyuncs.com";//填写明文accessKeyId和accessKeySecret,加密官网有OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("**********", "********** ");OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);//下面3个参数依次为bucket名,Object名,上传文件路径PutObjectRequest put = new PutObjectRequest("qhtmedia", objectname, path);if(path==null||path.equals("")){detail.setText("请选择视频!!!!");return;}tv.setText("正在上传中....");pb.setVisibility(View.VISIBLE);// 异步上传,可以设置进度回调put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {@Overridepublic void onProgress(PutObjectRequest request, long currentSize, long totalSize) {Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);}});@SuppressWarnings("rawtypes")OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {@Overridepublic void onSuccess(PutObjectRequest request, PutObjectResult result) {Log.d("PutObject", "UploadSuccess");//回调为子线程,所以去UI线程更新UIrunOnUiThread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtv.setText("UploadSuccess");pb.setVisibility(ProgressBar.INVISIBLE);}});}@Overridepublic void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {// 请求异常runOnUiThread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubpb.setVisibility(ProgressBar.INVISIBLE);tv.setText("Uploadfile,localerror");}});if (clientExcepion != null) {// 本地异常如网络异常等clientExcepion.printStackTrace();}if (serviceException != null) {// 服务异常tv.setText("Uploadfile,servererror");Log.e("ErrorCode", serviceException.getErrorCode());Log.e("RequestId", serviceException.getRequestId());Log.e("HostId", serviceException.getHostId());Log.e("RawMessage", serviceException.getRawMessage());}}});// task.cancel(); // 可以取消任务
//       task.waitUntilFinished(); // 可以等待直到任务完成
}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == PHOTO_REQUEST_GALLERY) {// 从相册返回的数据if (data != null) {// 得到视频的全路径Uri uri = data.getData();//转化为String路径getRealFilePath(MainActivity.this,uri);}} super.onActivityResult(requestCode, resultCode, data);}/* 下面是4.4后通过Uri获取路径以及文件名一种方法,比如得到的路径 /storage/emulated/0/video/20160422.3gp,通过索引最后一个/就可以在String中截取了*/public  void getRealFilePath( final Context context, final Uri uri ) {if ( null == uri ) return ;final String scheme = uri.getScheme();String data = null;if ( scheme == null )data = uri.getPath();else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {data = uri.getPath();} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );if ( null != cursor ) {if ( cursor.moveToFirst() ) {int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );if ( index > -1 ) {data = cursor.getString( index );}}cursor.close();}}path=data;String b = path.substring(path.lastIndexOf("/") + 1, path.length());//最后的得到的b就是:20160422.3gpdetail.setText(b);}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
public class PlayVideoActivity extends ActionBarActivity {private VideoView mVideoView;private TextView tvcache;private String localUrl,objectname;private ProgressDialog progressDialog = null;
//  private String remoteUrl = "http://f02.v1.cn/transcode/14283194FLVSDT14-3.flv";
//  private static final int READY_BUFF = 600 * 1024*1000;//当视频缓存到达这个大小时开始播放
//  private static final int CACHE_BUFF = 500 * 1024;//当网络不好时建立一个动态缓存区,避免一卡一卡的播放
//  private boolean isready = false;private boolean iserror = false;private int errorCnt = 0;private int curPosition = 0;private long mediaLength = 0;private long readSize = 0;private InputStream inputStream;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.playvideo);findbyid();init();downloadview();}private void init() {// TODO Auto-generated method stubIntent intent = getIntent();objectname= intent.getStringExtra("objectname");this.localUrl = intent.getStringExtra("cache");mVideoView.setMediaController(new MediaController(this));
//      if (!URLUtil.isNetworkUrl(remoteUrl)) {//          mVideoView.setVideoPath(remoteUrl);
//          mVideoView.start();
//      }mVideoView.setOnPreparedListener(new OnPreparedListener() {public void onPrepared(MediaPlayer mediaplayer) {dismissProgressDialog();mVideoView.seekTo(curPosition);mediaplayer.start();}});mVideoView.setOnCompletionListener(new OnCompletionListener() {public void onCompletion(MediaPlayer mediaplayer) {curPosition = 0;mVideoView.pause();}});mVideoView.setOnErrorListener(new OnErrorListener() {public boolean onError(MediaPlayer mediaplayer, int i, int j) {iserror = true;
//              errorCnt++;mVideoView.pause();showProgressDialog();return true;}});}private void showProgressDialog() {mHandler.post(new Runnable() {@Overridepublic void run() {if (progressDialog == null) {progressDialog = ProgressDialog.show(PlayVideoActivity.this,"视频缓存", "正在努力加载中 ...", true, false);}}});}private void dismissProgressDialog() {mHandler.post(new Runnable() {@Overridepublic void run() {if (progressDialog != null) {progressDialog.dismiss();progressDialog = null;} }});}private void downloadview() {// TODO Auto-generated method stubString endpoint = "http://oss-cn-shanghai.aliyuncs.com";// 明文设置secret的方式建议只在测试时使用,更多鉴权模式请参考官网OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("**********", "**********");OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);// 构造下载文件请求GetObjectRequest get = new GetObjectRequest("qhtmedia", objectname);@SuppressWarnings("rawtypes")OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {@Overridepublic void onSuccess(GetObjectRequest request, GetObjectResult result) {// 请求成功回调Log.d("Content-Length", "" + result.getContentLength());//拿到输入流和文件长度inputStream = result.getObjectContent();mediaLength=result.getContentLength();showProgressDialog();byte[] buffer = new byte[2*2048];int len;FileOutputStream out = null;
//              long lastReadSize = 0;//建立本地缓存路径,视频缓存到这个目录if (localUrl == null) {localUrl = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/VideoCache/"+ System.currentTimeMillis() + ".mp4";}Log.d("localUrl: " , localUrl);File cacheFile = new File(localUrl);if (!cacheFile.exists()) {cacheFile.getParentFile().mkdirs();try {cacheFile.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}readSize = cacheFile.length();try {//将缓存的视频转换为流out = new FileOutputStream(cacheFile, true);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (mediaLength == -1) {return;}mHandler.sendEmptyMessage(VIDEO_STATE_UPDATE);try {while ((len = inputStream.read(buffer)) != -1) {// 处理下载的数据try{out.write(buffer, 0, len);readSize += len;} catch (Exception e) {e.printStackTrace();}}mHandler.sendEmptyMessage(CACHE_VIDEO_END);} catch (IOException e) {e.printStackTrace();}finally {if (out != null) {try {out.close();} catch (IOException e) {}}if (inputStream != null) {try {inputStream.close();} catch (IOException e) {}}}}@Overridepublic void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {// 请求异常if (clientExcepion != null) {// 本地异常如网络异常等clientExcepion.printStackTrace();}if (serviceException != null) {// 服务异常Log.e("ErrorCode", serviceException.getErrorCode());Log.e("RequestId", serviceException.getRequestId());Log.e("HostId", serviceException.getHostId());Log.e("RawMessage", serviceException.getRawMessage());}}});// task.cancel(); // 可以取消任务//       task.waitUntilFinished(); // 如果需要等待任务完成}private final static int VIDEO_STATE_UPDATE = 0;private final static int CACHE_VIDEO_END = 3;private final Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case VIDEO_STATE_UPDATE:double cachepercent = readSize * 100.00 / mediaLength * 1.0;String s = String.format("已缓存: [%.2f%%]", cachepercent);
//              }//缓存到达100%时开始播放if(cachepercent==100.0||cachepercent==100.00){mVideoView.setVideoPath(localUrl);mVideoView.start();String s1 = String.format("已缓存: [%.2f%%]", cachepercent);tvcache.setText(s1);return;}tvcache.setText(s);mHandler.sendEmptyMessageDelayed(VIDEO_STATE_UPDATE, 1000);break;case CACHE_VIDEO_END:if (iserror) {mVideoView.setVideoPath(localUrl);mVideoView.start();iserror = false;}break;}super.handleMessage(msg);}};private void findbyid() {// TODO Auto-generated method stubmVideoView = (VideoView) findViewById(R.id.bbvideoview);tvcache = (TextView) findViewById(R.id.tvcache);}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231

代码中注释已经很清楚了。有问题的大家可以问我,最后附上源码地址: 
https://github.com/qht1003077897/android-vedio-upload-and-download.git

安卓手把手教你结合阿里云OSS存储实现视频(音频,图片)的上传与下载相关推荐

  1. 微信小程序 - 超详细 “纯前端“ 将文件上传到阿里云 OSS,最新阿里云 OSS 直传音视频、图片、word、excel、ppt、office 文档(全程无需后端,前端文件直传阿里云oss服务器)

    前言 网上的教程乱七八糟却文件少代码(并且没注释),而且都已经很老了,对于新手来说真的无从下手. 本文站在新手小白的角度,实现微信小程序开发中,"前端直传" 上传文件到阿里云oss ...

  2. 阿里云MaxCompute中pyODPS的使用:多线程上传、下载、分区

    文章目录 1 初始化入口 2 java可实现:SQLTask配合Tunnel实现大量数据导出 3 pyODPS 3.1 sql读入 3.2 DataFrame 3.2.1 dataframe读入 3. ...

  3. 手把手教你创建阿里云平台

    手把手教你创建阿里云平台 创建: 1.打开阿里云平台官网https://account.aliyun.com/,注册账号 2.登录账号,找到产品界面并创建产品 3.新建产品,设置如下 4.产片创建成功 ...

  4. 手把手教你在阿里云ECS上搭建惊艳的博客

    手把手教你在阿里云ECS上搭建惊艳的博客 相信大多数人都有自己搭建博客网站的想法,本文就手把手一步一步的进行,最终结果类似如下样式: 网站软件的选择 软件选择成熟而免费的WordPress,WordP ...

  5. mysql数据库备份到oss_备份MySQL数据库并上传到阿里云OSS存储

    1. 环境配置 要将本地文件上传到阿里云oss中, 必须使用阿里云提供的工具 ossutil, 有32位,也有64位的, Linux和Windows都有.具体可以到阿里云官网下载 本文以Linux系统 ...

  6. django图片上传到oss_django 配置阿里云OSS存储media文件的例子

    1. 安装django-aliyun-oss2-storage包 linux上用 pip install django-aliyun-oss2-storage 无报错,顺利安装 windows上报错: ...

  7. 从AWS S3换成阿里云OSS存储所踩的坑

    因业务需要,AWS S3 不能使用了,要换成阿里云OSS存储和下载.简单作以记录,以作备忘. 1.参照https://help.aliyun.com/product/31815.html?spm=51 ...

  8. 前端(react)上传到阿里云OSS存储 实例

    需求背景 由于现有的后台管理系统,上传的视频越来越大,加上上传视频较慢,后端小哥提出直接从前端上传视频或者其他文件到阿里云OSS存储. 阿里云OSS 阿里云OSS文档介绍,这里不做过多赘述 安装 原本 ...

  9. 使用PicGo+阿里云OSS实现md文档图片上传

    使用PicGo+阿里云OSS实现md文档图片上传 这次给大家带来的是PicG0+阿里云Oss+typora的图床环境搭建,帮助大家提高工作效率+写博客速度! 1.typora安装 给大家一个链接:ty ...

最新文章

  1. R可视化散点图并绘制回归曲线
  2. 基于window-based模板的多View程序(转)
  3. Java之旅(二)--- ServletContext
  4. log4cxx体系结构
  5. JBPM回退功能的实现
  6. Spring Cloud(四) API网关Zuul
  7. Python拼接字符串的7种方法总结
  8. linux设置挂载服务端防火墙_Linux Tomcat使用之前预配置(端口开放关闭 防火墙设置 硬盘挂载 安装文件)...
  9. IOS 4.0 以上版本 home键退出 后台执行代码
  10. WinExec, ShellExecute,CreateProcess的对比
  11. sonar-checkstyle plugin源码
  12. (转)mssql2005生成表字典
  13. 匿名函数自我调用_Python中的匿名函数及递归思想简析
  14. 如何将本地代码推送至远程仓库
  15. PHP查询文件扩展名
  16. 知识竞赛的环节主题文件准备的四大步骤及重要提示
  17. WINDOWS各类执行程序的接口总结
  18. D3D游戏关于窗口中如何精确确定鼠标位置的相关讨论
  19. Android Canvas API总结和使用方法
  20. ApacheCN 翻译/校对/笔记整理活动进度公告 2019.10.18

热门文章

  1. 第三届5G创新发展高峰论坛在北京召开
  2. http与https概述
  3. Log4j2使用详解
  4. Java下的路径getPath,getAbsolutePath和getCanonicalPath
  5. SkinnedMeshRenderer骨骼动画的模型位置问题
  6. std::string::empty
  7. setTimeout异步执行
  8. 不一样的动图-APNG
  9. 软考高级系统架构设计师:基于ODP的架构师实践
  10. 前端流行使用的五种框架对比