安卓手把手教你结合阿里云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);
         }
}
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);
    }
}

代码中注释已经很清楚了。有问题的大家可以问我,最后附上源码地址:

https://github.com/qht1003077897/android-vedio-upload-and-download.git

时间: 2024-07-31 14:35:14

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

jeesz分布式架构集成阿里云oss存储

1. 服务接口定义 /** * 文件上传  1:头像 2:显示图片 3:个人封面  :4:基础图片 * @param request * @param response * @param uid 用户id * @param userType 文件上传  1:头像 2:显示图片 3:个人封面  :4:基础图片 0:视频 * @param files 上传的文件对象 * @return * @throws Exception */ @RequestMapping(value = "/upload/b

php将图片存储在阿里云oss存储上

一个配置文件 创建两个方法 1.上传方法 /** * 存储文件 * * @param $srcFile * @param $desFile * @throws Exception */public function storage_save($srcPath, $desPath){ //配置 $accessKeyId = ''; $accessKeySecret = ''; $endpoint = ''; $bucket = ''; $ossClient = new \OSS\OssClient

阿里云oss存储作一级源站与本地mfs存储作二级源站方案

在百度cdn新建cdn域名,主源站地址填写阿里oss的Bucket 域名meizu-news.oss-cn-hangzhou.aliyuncs.com 2.在百度回源配置里,配置回源hosts 3.在阿里云oss存储页面配置,镜像回二级mfs源站,镜像回源具体说明可参考阿里云官方文档:https://help.aliyun.com/document_detail/31865.html?spm=5176.8466029.retrieving.1.4e9d1450qhzYuu 4.填入mfs的LVS

超详细, 手把手教你搭建阿里云个人站点

# 搭建阿里云服务器 [TOC] ## 0. 费用 > 第一步先交代一下大家比较关心的东东, 以下是所有费用: * 阿里云服务器: 三年 229 元 ![f52e0b7ac813e6a7473d44e750c0e7ff.png](evernotecid://7D5162EA-5D37-473F-9C81-E2FEC23DD3B2/appyinxiangcom/18499762/ENResource/p482) * 域名: 三年: 150 元 ![4043d91cc2099623d517013ac

阿里云OSS存储开发(一)

Step 1. 初始化一个OSSClient OSSClient是与OSS服务交互的客户端,SDK的OSS操作都是通过OSSClient完成的. 下面代码新建了一个OSSClient: using Aliyun.OpenServices.OpenStorageService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Ta

阿里云OSS存储开发

Step 1. 初始化一个OSSClient        OSSClient是与OSS服务交互的客户端,SDK的OSS操作都是通过OSSClient完成的. 下面代码新建了一个OSSClient: using Aliyun.OpenServices.OpenStorageService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threa

J2EE分布式架构集成阿里云OSS存储

摘要: 1. 服务接口定义 / 文件上传 1:头像 2:显示图片 3:个人封面 :4:基础图片 @param request @param response @param uid 用户id @param userType 文件上传 1:头像 2:显示图片 3:个人封面 :4:基础图片 0:视频 @param files 上传的文件对象 * @return 服务接口定义 /** 文件上传 1:头像 2:显示图片 3:个人封面 :4:基础图片 *@paramrequest *@paramrespon

使用阿里云oss

写这篇博文的原因是公司有个项目需要用到阿里云来存放用户头像文件.后期软件安装版本也可能需要存进去,然后折腾了两天终于摸熟了一点皮毛,在这里给大家简单介绍下. 一.初识对象存储oss 1.进入阿里云控制台后,搜oss,选择“对象存储oss”,如图 首次使用,应该是要确定授权开启对象存储oos的,确定之后,会生产accesskeyid和accesssecret,记得保存下来,后面使用都需要这两个值 开启后如图 接下来,点击“安全令牌”获得roleArn, 输入手机验证码后获得如图,这个roleArn

thinkphp集成系列之阿里云oss

web2.0时代:除了纯信息展示类的网站:基本都是有文件上传功能的: 最不济你得让用户换个头像吧:但是随着业务的发展: 如果上传的文件都和网站程序源代码放在一起:那是有相当多的弊端的: 1:静态文件会占用大量带宽: 2:服务器的成本略高: 常规的做法是把php源代码放到一台服务器上:图片等静态文件放在另一台服务器上: 当一个神奇的“云”时代的到来后:一切就变的更加简单了: 在业务还比较小的时候:我们无需大费周折的去搞一台静态文件服务器:直接使用第三方的即可: 好了:洛里啰嗦了半天:下面请出本篇博