Android用百度云上传文件

1.先在百度云申请账号

2.创建应用,可以创建多个,不同的应用有不同的应用ID,API Key,Secret Key

3.API管理-API列表里开启PCS API,同时创建文件目录

建立android项目,将SDK中lib的JAR包拷到项目的libs文件夹下

代码里先用APIKEY登录

BaiduOAuth oauthClient = new BaiduOAuth();
  oauthClient.startOAuth(this, mbApiKey, new String[]{"basic", "netdisk"}, new BaiduOAuth.OAuthListener() {
   @Override
   public void onException(String msg) {
    Toast.makeText(getApplicationContext(), "Login failed " + msg, Toast.LENGTH_SHORT).show();
   }
   @Override
   public void onComplete(BaiduOAuthResponse response) {
    if(null != response){
     mbOauth = response.getAccessToken();
     Toast.makeText(getApplicationContext(), "Token: " + mbOauth + "    User name:" + response.getUserName(), Toast.LENGTH_SHORT).show();
    }
   }
   @Override
   public void onCancel() {
    Toast.makeText(getApplicationContext(), "Login cancelled", Toast.LENGTH_SHORT).show();
   }
  });

上传的时候mbRootPath=“/apps/mybst”  mybst是开启PCS API时创建的文件目录名

     if(null != mbOauth){

      Thread workThread = new Thread(new Runnable(){
    public void run() {
     
     String tmpFile = "/storage/sdcard0/zzzz.jpg";
    // String tmpFile = "/mnt/sdcard/DCIM/File/1.txt";
     
        BaiduPCSClient api = new BaiduPCSClient();
        api.setAccessToken(mbOauth);
        
        final BaiduPCSActionInfo.PCSFileInfoResponse response = api.uploadFile(tmpFile, mbRootPath + "/zzz.jpg", new BaiduPCSStatusListener(){

      @Override
      public void onProgress(long bytes, long total) {
       // TODO Auto-generated method stub
       
       
       final long bs = bytes;
       final long tl = total;

          mbUiThreadHandler.post(new Runnable(){
           public void run(){
            Toast.makeText(getApplicationContext(), "total: " + tl + "    sent:" + bs, Toast.LENGTH_SHORT).show();
           }
          });      
      }
      
      @Override
      public long progressInterval(){
       return 1000;
      }
        });
        
        mbUiThreadHandler.post(new Runnable(){
         public void run(){
          Toast.makeText(getApplicationContext(), response.status.errorCode + "  " + response.status.message + "  " + response.commonFileInfo.blockList, Toast.LENGTH_SHORT).show();
         }
        }); 
    }
   });
   
      workThread.start();

 

 

你可能感兴趣的:(Android用百度云上传文件)