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

首先,明白阿里云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;// 从相册中选择
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       findbyid();
    }
    private void findbyid() {
        // TODO Auto-generated method stub
        selectvideo= (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() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent 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() {
            @Override
            public void onClick(View v) {
            beginupload();
            }
        });
    }
        //从图库选择视频
    public void selectvideo(View view)
    {
        //跳到图库
          Intent intent = new Intent(Intent.ACTION_PICK);
          //选择的格式为视频,图库中就只显示视频(如果图片上传的话可以改为image/*,图库就只显示图片)
                   intent.setType("video/*");
                   // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY
                   startActivityForResult(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>() {
            @Override
            public 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>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                //回调为子线程,所以去UI线程更新UI
                runOnUiThread(new Runnable() {
                @Override
                    public void run() {
                        // TODO Auto-generated method stub
                  tv.setText("UploadSuccess");
                  pb.setVisibility(ProgressBar.INVISIBLE);
                }
                });
            }
            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                runOnUiThread(new Runnable() {
                    @Override
                        public void run() {
                            // TODO Auto-generated method stub
                        pb.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(); // 可以等待直到任务完成
}
         @Override
              protected 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.3gp
             detail.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;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playvideo);
        findbyid();
        init();
        downloadview();
    }



    private void init() {
        // TODO Auto-generated method stub
        Intent 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() {
            @Override
            public void run() {
                if (progressDialog == null) {
                    progressDialog = ProgressDialog.show(PlayVideoActivity.this,
                    "视频缓存", "正在努力加载中 ...", true, false);
                }
            }
        });
    }

    private void dismissProgressDialog() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                } 
            }
        });
    }


    private void downloadview() {
        // TODO Auto-generated method stub
        String 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>() {
            @Override
            public 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 block
                        e.printStackTrace();
                    }
                }
                readSize = cacheFile.length();
                try {
                //将缓存的视频转换为流
                    out = new FileOutputStream(cacheFile, true);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.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) {
                        }
                    }
                }
            }
            @Override
            public 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() {
        @Override
        public 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 stub
        mVideoView = (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

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值