android上传图片到七牛云存储demo

第一步:在七牛云官网注册账号,开通七牛云存储,并创建一个存储空间。

android上传图片到七牛云存储demo_第1张图片


第二步:在个人中心获取AccessKey和SecretKey。

android上传图片到七牛云存储demo_第2张图片

第三步:开始敲代码了;

  1,添加依赖:

 compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.loopj.android:android-async-http:1.4.9'

    compile 'com.qiniu:qiniu-android-sdk:7.3.+'
    compile 'com.qiniu:happy-dns:0.2.10'

2,添加权限

 
 
3,具体代码

QnUploadHelper.java

public class QnUploadHelper {
    private  final String TAG = QnUploadHelper.class.getSimpleName();
    //七牛后台的key
    private  String AccessKey;
    //七牛后台的secret
    private  String SecretKey;

    private  String BucketName="你创建的资源空间";

    private  final String MAC_NAME = "HmacSHA1";
    private  final String ENCODING = "UTF-8";

    private static Configuration configuration;

    private static long delayTimes = 3029414400l; //有效时间

	//初始化
    public static void init(String accessKey, String secretKey) {
        AccessKey = accessKey;
        SecretKey = secretKey;
        configuration = new Configuration.Builder().build();
    }

    /**
     * 上传
     *
     //* @param keys 上传到空间后的文件名的名字
     * @param path   上传文件的路径地址
	   @param callBack 回调接口
     */
    public static void uploadPic(final String path, final String keys, final UploadCallBack callBack) {
        try {
            // 1:第一种方式 构造上传策略
            JSONObject _json = new JSONObject();
            _json.put("deadline", delayTimes);
            _json.put("scope", BucketName);
            String _encodedPutPolicy = UrlSafeBase64.encodeToString(_json
                    .toString().getBytes());

            byte[] _sign = HmacSHA1Encrypt(_encodedPutPolicy, SecretKey);

            String _encodedSign = UrlSafeBase64.encodeToString(_sign);
			
            //生成token
            final String _uploadToken = AccessKey + ':' + _encodedSign + ':'
                    + _encodedPutPolicy;

            //重用uploadManager。一般地,只需要创建一个uploadManager对象
            UploadManager uploadManager = new UploadManager(configuration);

            uploadManager.put(path, keys, _uploadToken,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info,
                                             JSONObject response) {
                            Log.d(TAG,"response = " + response);
                            if (info.isOK()) {
                                callBack.success(key);
                            } else
                                callBack.fail(key, info);
                        }
                    }, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 使用 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);
    }

//反馈接口
    public interface UploadCallBack {
        void success(String url);

        void fail(String key, ResponseInfo info);
    }

mainActivity.java

public class MainActivity extends Activity {
    ImageButton imageButton;
    String photoPath;
    Bitmap bitmap;
    Button btnUpload;
    
   //七牛后台的key
    private static String AccessKey="你的AccessKey";
    //七牛后台的secret
    private static String SecretKey=SecretKey;
	
    @Override
     protected void onCreate(Bundle savedInstanceState) {
                     super.onCreate(savedInstanceState);
                       setContentView(R.layout.activity_main);
                        

                     init();

        }

    private void init() {
        imageButton=findViewById(R.id.downloadimageView);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //使用Intent触发选择Action
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                //打开系统提供的图片选择界面
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                //传参以在返回本界面时触发加载图片的功能
                startActivityForResult(intent, 0x1);

            }
        });
		
		//初始化七牛云
		 QnUploadHelper.init(appKey,appSecret);
		 
        btnUpload=findViewById(R.id.upload);
        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               QnUploadHelper.uploadPic(photoPath, "test_qiniuniubi", new QnUploadHelper.UploadCallBack() {
                   @Override
                   public void success(String url) {
                       Log.i("image_uri",url);
                   }

                   @Override
                   public void fail(String key, ResponseInfo info) {
                       Log.i("key",key+info.error);
                   }
               });
            }
        });

       
    }


				 
    //在选择图片后返回本界面调用此方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            if (data != null) {

                ContentResolver resolver = getContentResolver();
                try {
                    // 获取圖片URI
                    Uri uri = data.getData();
                    // 将URI转换为路径:
                    String[] proj = { MediaStore.Images.Media.DATA };
                    Cursor cursor = managedQuery(uri, proj, null, null, null);
                    //  这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    // 最后根据索引值获取图片路径
                     photoPath = cursor.getString(column_index);

                    // 压缩成800*480
                    bitmap = BitmapFactory.decodeFile(photoPath);
                    // 设置imageview显示图片
                    imageButton.setImageBitmap(bitmap);
                    // 设置textview显示路径
                     Log.i("aaa","photoPath"+photoPath);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }
   
 }
main_activity.xml


    

    

    


你可能感兴趣的:(Android)