Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓手把手教你結合阿裡雲OSS存儲實現視頻(音頻,圖片)的上傳與下載

安卓手把手教你結合阿裡雲OSS存儲實現視頻(音頻,圖片)的上傳與下載

編輯:關於Android編程

首先,明白阿裡雲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後台看到這個資源。再點擊網絡播放按鈕,從後台下載這個視頻並播放,同時實現了緩存到本地。<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> 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() { @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() { @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() {
            @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

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved