Android圖片上傳到阿里雲OSS小案例

小林子飛飛飛發表於2018-08-23

官方文件和SDK:API&SDK
原始碼點選這裡

一、在阿里雲開通OOS(必須註冊有阿里雲賬戶,並開通OSS服務)

1.在管理控制檯找到OOS並開通
2.點選儲存空間,建立bucket
這裡寫圖片描述這裡寫圖片描述

二、整合

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 將無法正常工作。

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

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然後將需要的值複製貼上到工具類對應位置
這裡寫圖片描述
(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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/upload_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="上傳圖片"/>

</android.support.constraint.ConstraintLayout>

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、結果驗證
這裡寫圖片描述
看到如上結果,那恭喜你大功告成了。
[ps]有的人可能有個地方會報錯,當然不能原原本本的抄了
這裡寫圖片描述
這裡要換成你自己的全域性Application Content,
這裡寫圖片描述
另外,一個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();
                }
            }
        }
    }
}

相關文章