七牛は写真のツール類をアップロードして、みんなが使うのに便利です

7714 ワード

github形式はこちらです
https://github.com/guaju/AdouLive/blob/master/app/src/main/java/com/guaju/adoulive/qiniu/QiniuUploadHelper.java
ここに貼って
import android.util.Log;

import com.guaju.adoulive.httputil.OkHttpHelper;
import com.orhanobut.logger.Logger;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.UrlSafeBase64;

import org.json.JSONObject;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by guaju on 2017/11/2.
 *   7     
 *
 */

public class QiniuUploadHelper {

    private static String mSpaceName;
    private static String mSecretKey;
    private static String mAccessKey;


    private static boolean isCancelled=false;
    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";
    // static final  String SPACENAME="my-bucket";
//  static final String AccessKey="MY_ACCESS_KEY";
//  static final String SecretKey="MY_SECRET_KEY";
    private static UploadManager uploadManager;

    //    uploadManager
    public  static void  init(String spaceName,String secretKey,String accessKey){
        mAccessKey=accessKey;
        mSecretKey=secretKey;
        mSpaceName=spaceName;

        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        //      ,     。   256K
                .putThreshhold(1024 * 1024)   //         。  512K
                .connectTimeout(10)           //     。  10 
                .useHttps(true)               //     https    
                .responseTimeout(60)          //        。  60 
                .zone(FixedZone.zone0)        //     ,           、    、  IP。
                .build();
        //  uploadManager。   ,       uploadManager  
        uploadManager = new UploadManager(config);
    }
    //     ?        token 

    /**
     *
     * @param picName       ,       
     * @return
     */
    public static String calcToken(String picName) throws Exception {
        //1、      
        String scope=mSpaceName+":"+picName;
        long deadline= (System.currentTimeMillis()+3000)/1000;
//        long deadline= 1451491200;
        //TokenBean.ReturnBody returnBody = new TokenBean.ReturnBody("$(fname)", "$(fsize)", "$(imageInfo.width)", "$(imageInfo.height)", "$(etag)");
        TokenBean tokenBean = new TokenBean(scope, deadline);
        //2、        json
        String putPolicy = OkHttpHelper.getInstance().gson.toJson(tokenBean);
        //3、URL     Base64   
        String encodedPutPolicy = UrlSafeBase64.encodeToString(putPolicy.getBytes());
        //4、      (AK/SK)               HMAC-SHA1  :
        byte[] sign = HmacSHA1Encrypt(encodedPutPolicy, mSecretKey);
        //5、     URL   Base64  :
        String encodedSign = UrlSafeBase64.encodeToString(sign);
        //6、     (AK/SK)、encodedSign   encodedPutPolicy       :     :
        String uploadToken =mAccessKey + ':' + encodedSign + ':' + encodedPutPolicy;
        return uploadToken;

    }
    /**
     *    HMAC-SHA1       encryptText    
     *
     * @param encryptText        
     * @param encryptKey    
     * @return
     * @throws Exception
     */
    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey)
            throws Exception {


        byte[] data = encryptKey.getBytes(ENCODING);
        //                ,               
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        //        Mac      Mac   
        Mac mac = Mac.getInstance(MAC_NAME);
        //          Mac   
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        //    Mac   
        return mac.doFinal(text);
    }

    /**
     *            
     * @param filePath      
     * @param picName             
     */
    public static void uploadPic(String filePath,String picName,UpCompletionHandler handler) throws Exception {
        String data =filePath;
        String key = picName;
        String token= calcToken(picName);
        uploadManager.put(data, key, token,
               handler, null);
    }

    /**
     *              
     * @param filePath
     * @param picName
     * @param token
     */
    public  static void uploadPicWithProgress(String filePath,String picName,String token){
        uploadManager.put(filePath, picName, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res  hash、key   ,              
                        if(info.isOK()) {
                            Logger.i("qiniu", "Upload Success");
                        } else {
                            Logger.i("qiniu", "Upload Fail");
                            //    ,     info          ,            
                        }
                        Log.i("qiniu", key + ",\r
" + info + ",\r
" + res); } }, new UploadOptions(null,null, false, new UpProgressHandler(){ public void progress(String key, double percent){ Log.i("qiniu", key + ": " + percent); } }, null)); } /** * * @param filePath * @param picName * @param token */ public static void uploadPicCanCancle(String filePath,String picName,String token){ uploadManager.put(filePath, picName, token, new UpCompletionHandler() { @Override public void complete(String key, ResponseInfo info, JSONObject res) { //res hash、key , if(info.isOK()) { Logger.i("qiniu", "Upload Success"); } else { Logger.i("qiniu", "Upload Fail"); // , info , } Log.i("qiniu", key + ",\r
" + info + ",\r
" + res); } }, new UploadOptions(null,null, false, new UpProgressHandler(){ public void progress(String key, double percent){ Log.i("qiniu", key + ": " + percent); } }, new UpCancellationSignal(){ public boolean isCancelled(){ return isCancelled; } })); } /** * * @param value */ public static void setCancle(boolean value){ isCancelled=value; } }
ok、呼び出すときはクラスの
uploadPic(String filePath,String picName,UpCompletionHandler handler) 

方法でいい
注意:ネットワークの状態が悪すぎる場合は、修正をお勧めします.
long deadline= (System.currentTimeMillis()+3000)/1000;
この画像の生存時間は、上の3000を15000に変更すれば対応できるはずですが、実際に必要なものを見なければなりません.何か問題があれば、コメントしてください.