Android图片上传到阿里云OSS小案例

官方文档和SDK:API&SDK
【 源代码点击这里 】

一、在阿里云开通OOS(必须注册有阿里云账户,并开通OSS服务)

1.在管理控制台找到OOS并开通
2.点击存储空间,创建bucket
Android图片上传到阿里云OSS小案例_第1张图片Android图片上传到阿里云OSS小案例_第2张图片

二、集成

1、 Android SDK开发包
Android Studio方式(推荐) Maven依赖

 dependencies {
      implementation 'com.aliyun.dpa:oss-android-sdk:2.3.0'
      implementation 'com.squareup.okhttp3:okhttp:3.10.0'
      implementation 'com.squareup.okio:okio:1.9.0'
  }

2、权限设置
在 AndroidManifest.xml 文件中已经配置了这些权限,否则,SDK 将无法正常工作。

    
    
    
    
    

3.混淆设置
修改 [项目名\app\proguard-rules.pro]路径下的proguard-rules.pro文件

    -keep class com.alibaba.sdk.android.oss.** { *; }
    -dontwarn okio.**
    -dontwarn org.apache.commons.codec.binary.**

4.写工具类
(1)首先要有4个数据
END_POINT 、BUCKET_NAME 、Access Key ID、Access Key Secret
创建你的Access Key然后将需要的值复制粘贴到工具类对应位置
Android图片上传到阿里云OSS小案例_第3张图片
(2)写工具类,UploadHelper

package com.smxy.lj.utils;

import android.text.Editable;
import android.text.format.DateFormat;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import org.litepal.LitePalApplication;

import java.io.File;
import java.util.Date;


public class UploadHelper {

    //与个人的存储区域有关
    private static final String ENDPOINT = "你的END_POINT ";
    //上传仓库名
    private static final String BUCKET_NAME = "你的BUCKET_NAME ";

    private static OSS getOSSClient() {
        OSSCredentialProvider credentialProvider =
                new OSSPlainTextAKSKCredentialProvider("你的Access Key ID" , 
                "你的Access Key Secret");
        return new OSSClient( LitePalApplication.getContext(), ENDPOINT, credentialProvider);
    }

    /**
     * 上传方法
     *
     * @param objectKey 标识
     * @param path      需上传文件的路径
     * @return 外网访问的路径
     */
    private static String upload(String objectKey, String path) {
        // 构造上传请求
        PutObjectRequest request =
                new PutObjectRequest(BUCKET_NAME,
                        objectKey, path);
        try {
            //得到client
            OSS client = getOSSClient();
            //上传获取结果
            PutObjectResult result = client.putObject(request);
            //获取可访问的url
            String url = client.presignPublicObjectURL(BUCKET_NAME, objectKey);
            //格式打印输出
            MyLog.e(String.format("PublicObjectURL:%s", url));
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 上传普通图片
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadImage(String path) {
        String key = getObjectImageKey(path);
        return upload(key, path);
    }

    /**
     * 上传头像
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadPortrait(String path) {
        String key = getObjectPortraitKey(path);
        return upload(key, path);
    }

    /**
     * 上传audio
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadAudio(String path) {
        String key = getObjectAudioKey(path);
        return upload(key, path);
    }


    /**
     * 获取时间
     *
     * @return 时间戳 例如:201805
     */
    private static String getDateString() {
        return DateFormat.format("yyyyMM", new Date()).toString();
    }

    /**
     * 返回key
     *
     * @param path 本地路径
     * @return key
     */
    //格式: image/201805/sfdsgfsdvsdfdsfs.jpg
    private static String getObjectImageKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("image/%s/%s.jpg", dateString, fileMd5);
    }

    //格式: portrait/201805/sfdsgfsdvsdfdsfs.jpg
    private static String getObjectPortraitKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("portrait/%s/%s.jpg", dateString, fileMd5);
    }

    //格式: audio/201805/sfdsgfsdvsdfdsfs.mp3
    private static String getObjectAudioKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("audio/%s/%s.mp3", dateString, fileMd5);
    }

}

三、测试

(按钮点击上传一张图片,因为测试,我就把图片路径写死了)
1、写一个leyout




    

2.对应的Java类

package com.smxy.lj.myfile;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;

import com.smxy.lj.officedemo.R;
import com.smxy.lj.utils.MyLog;
import com.smxy.lj.utils.UploadHelper;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Uplode extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        
        setContentView( R.layout.activity_uplod );
        ButterKnife.bind( this );//绑定组件,以便引用
        
    }
    @OnClick(R.id.upload_btn)
    public void onClick(){
        UploadHelper uploadHelper = new UploadHelper();
        String uploaduel = uploadHelper.uploadPortrait("/storage/emulated/0/XRichText/1534936652406-");// “/storage/emulated/0/XRichText/1534936652406-”是我手机里一张图片的路径

//这个方法会返回OSS上图片的路径
        MyLog.e( "xxxx----testurl:" +uploaduel);
    }
}

3、结果验证
Android图片上传到阿里云OSS小案例_第4张图片
看到如上结果,那恭喜你大功告成了。
[ps]有的人可能有个地方会报错,当然不能原原本本的抄了
Android图片上传到阿里云OSS小案例_第5张图片
这里要换成你自己的全局Application Content,
Android图片上传到阿里云OSS小案例_第6张图片
另外,一个HashUtil.java

package com.smxy.lj.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @version 1.0.0
 *
 * 对文件或者字符串进行Hash算法,返回MD5值
 * GitHub:https://github.com/qiujuer/Genius-Android/blob/steady/steady/library/src/main/java/net/qiujuer/genius/util/HashUtils.java
 */
public class HashUtil {
    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'};

    private static String convertToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (byte a : b) {
            sb.append(HEX_DIGITS[(a & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[a & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * Get a String's HashCode
     *
     * @param str String
     * @return HashCode
     */
    public static String getMD5String(String str) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        md5.update(str.getBytes());
        return convertToHexString(md5.digest());
    }

    /**
     * Get a File's HashCode
     *
     * @param file File
     * @return HashCode
     */
    public static String getMD5String(File file) {
        // Create md5
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        // Stream
        InputStream in = null;
        byte[] buffer = new byte[1024];
        int numRead;
        // Read
        try {
            in = new FileInputStream(file);
            while ((numRead = in.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            return convertToHexString(md5.digest());
        } catch (Exception e) {
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

你可能感兴趣的:(Android)