Android Oss上傳圖片的使用示例
前言
前一陣項目中的上傳圖片改為上傳到阿里上,記錄一下實現(xiàn)的過程,方便以后查看。
參考資料:官方文檔
配置
Android studio添加依賴
dependencies {
compile 'com.aliyun.dpa:oss-android-sdk:2.4.5'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'
}
直接引入jar包(對Android studio 或者 Eclipse 都適用)
1.在官網(wǎng)下載 sdk 包
2.解壓后得到 jar 包,目前包括 aliyun-oss-sdk-android-x.x.x.jar、okhttp-3.x.x.jar 和 okio-1.x.x.jar
3.將以上 3 個 jar 包導(dǎo)入 libs 目錄
權(quán)限設(shè)置
確保AndroidManifest.xml 文件中已經(jīng)配置了這些權(quán)限,否則,SDK 將無法正常工作。
<uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
混淆設(shè)置
-keep class com.alibaba.sdk.android.oss.** { *; }
-dontwarn okio.**
-dontwarn org.apache.commons.codec.binary.**
實現(xiàn)過程
首先為了安全起見,采用的是STS鑒權(quán)模式,則要用到的數(shù)據(jù)都是從后臺獲得然后應(yīng)用到前臺的。
1.創(chuàng)建OSSClient (自己在這里命名為OssService)
OSSClient為OSS 服務(wù)的 Android 客戶端,它為調(diào)用者提供了一系列的方法,可以用來操作,管理存儲空間(bucket)和文件(object)等。
public class OssService {
private OSS oss;
private String bucket;
private picResultCallback callback;//回調(diào)接口
private String path=地址(后臺告訴);
public OssService(OSS oss, String bucket,picResultCallback callback) {
this.oss = oss;
this.bucket = bucket;
this.callback=callback;
}
/**object字段為圖片的上傳地址(具體地址的前綴后端給,這個是拼起
*來的一個路徑)
*localFile圖片的本地地址
*mProgress 進度條
*img 顯示圖片的控件
*type 類型
*/
public void asyncPutImage(String object, final String localFile, final ProgressBar mProgress, final ImageView img,String type) {
if (object.equals("")) {
Log.w("AsyncPutImage", "ObjectNull");
return;
}
File file = new File(localFile);
if (!file.exists()) {
Log.w("AsyncPutImage", "FileNotExist");
Log.w("LocalFile", localFile);
return;
}
// 構(gòu)造上傳請求
PutObjectRequest put = new PutObjectRequest(bucket, object, localFile);
put.setCallbackParam(new HashMap<String, String>() {
{
put("callbackUrl", path);
put("callbackBody", "filename=${object}&size=${size}&id=${x:id}&action=${x:action}");
//https://help.aliyun.com/document_detail/31989.html?spm=5176.doc31984.6.883.brskVg
}
});
HashMap<String, String> hashMap=new HashMap<>();
hashMap.put("x:id",id);
hashMap.put("x:action",type);
put.setCallbackVars(hashMap);
// 異步上傳時可以設(shè)置進度回調(diào)
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
int progress = (int) (100 * currentSize / totalSize);
mProgress.setProgress(progress);
}
});
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, final PutObjectResult result) {
Observable.just(result).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<PutObjectResult>() {
@Override
public void call(PutObjectResult putObjectResult) {
mProgress.setVisibility(View.GONE);
img.setColorFilter(null);
callback.getPicData(result,localFile);
}
});
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
String info = "";
// 請求異常
if (clientExcepion != null) {
// 本地異常如網(wǎng)絡(luò)異常等
clientExcepion.printStackTrace();
info = clientExcepion.toString();
}
if (serviceException != null) {
// 服務(wù)異常
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
info = serviceException.toString();
}
}
});
}
//成功的回調(diào)接口
public interface picResultCallback {
void getPicData(PutObjectResult data,String oldPath);
}
}
2.實現(xiàn)OssService的方法(在activity中)
public OssService initOSS(String endpoint, String bucket) {
OSSCredentialProvider credentialProvider;
credentialProvider = new STSGetter(tokenBean);
//設(shè)置網(wǎng)絡(luò)參數(shù)
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // 連接超時,默認15秒
conf.setSocketTimeout(15 * 1000); // socket超時,默認15秒
conf.setMaxConcurrentRequest(5); // 最大并發(fā)請求書,默認5個
conf.setMaxErrorRetry(2); // 失敗后最大重試次數(shù),默認2次
OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
return new OssService(oss, bucket, this);
}
3.重載OSSFederationCredentialProvider生成自己的獲取STS的功能(一般自動獲得token寫在這里,在getFederationToken()方法中,告訴它你獲得token的規(guī)則即可)
1>官方demo代碼(自動更新token)
public class OSSAuthCredentialsProvider extends OSSFederationCredentialProvider {
private String mAuthServerUrl;
private AuthDecoder mDecoder;
public OSSAuthCredentialsProvider(String authServerUrl) {
this.mAuthServerUrl = authServerUrl;
}
/**
* set auth server url
* @param authServerUrl
*/
public void setAuthServerUrl(String authServerUrl) {
this.mAuthServerUrl = authServerUrl;
}
/**
* set response data decoder
* @param decoder
*/
public void setDecoder(AuthDecoder decoder) {
this.mDecoder = decoder;
}
@Override
public OSSFederationToken getFederationToken() throws ClientException {
OSSFederationToken authToken;
String authData;
try {
URL stsUrl = new URL(mAuthServerUrl);
HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
conn.setConnectTimeout(10000);
InputStream input = conn.getInputStream();
authData = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
if (mDecoder != null) {
authData = mDecoder.decode(authData);
}
JSONObject jsonObj = new JSONObject(authData);
int statusCode = jsonObj.getInt("StatusCode");
if (statusCode == 200) {
String ak = jsonObj.getString("AccessKeyId");
String sk = jsonObj.getString("AccessKeySecret");
String token = jsonObj.getString("SecurityToken");
String expiration = jsonObj.getString("Expiration");
authToken = new OSSFederationToken(ak, sk, token, expiration);
} else {
String errorCode = jsonObj.getString("ErrorCode");
String errorMessage = jsonObj.getString("ErrorMessage");
throw new ClientException("ErrorCode: " + errorCode + "| ErrorMessage: " + errorMessage);
}
return authToken;
} catch (Exception e) {
throw new ClientException(e);
}
}
public interface AuthDecoder {
String decode(String data);
}
}
2>自己的代碼(因為自己的所有數(shù)據(jù)都是從后臺獲得的,而且結(jié)合rxjava沒有想到可以返回數(shù)據(jù)的方式,所以采用手動更新token的方式)
手動更新token的具體操作:
首先token的值存在MyApp中,第一次在進入需要用到token界面時候,先獲得token的值更新MyApp中的值并記錄當下的時間,如果下次再次進入任何一個需要用到token的界面的時候,則判斷時間是否過期,過期則重新請求token更新token的值。
public class STSGetter extends OSSFederationCredentialProvider {
private OSSFederationToken ossFederationToken;
String ak;
String sk;
String token ;
String expiration ;
public STSGetter(TokenBean bean) {
this.ak = bean.getCredentials().getAccessKeyId();
this.sk = bean.getCredentials().getAccessKeySecret();
this.token = bean.getCredentials().getSecurityToken();
this.expiration = bean.getCredentials().getExpiration();
}
public OSSFederationToken getFederationToken() {
return new OSSFederationToken(ak,sk,token,expiration);
}
}
4.實例化OSSClient,調(diào)用上傳圖片方法
//實例化OSSClient (自己是在onCreate()中實例化的,當然考慮到token的過期問題,也有在onResume()中再次實例化一次) ossService = initOSS(tokenBean.getBucket().getEndPoint(), tokenBean.getBucket().getBucketName()); //上傳圖片,需要根據(jù)自己的邏輯傳參數(shù) ossService.asyncPutImage(圖片在阿里上的存儲路徑, 本地路徑, ...);
5.回調(diào)處理圖片邏輯
/**
* 對圖片上傳回來的數(shù)據(jù)進行處理
* @param data
*/
@Override
public void getPicData(PutObjectResult data, String oldPath) {
Gson gson = new Gson();
OssUploadImage uploadImage = gson.fromJson(data.getServerCallbackReturnBody(), OssUploadImage.class);
........邏輯自己寫吧
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android基于OkHttp實現(xiàn)下載和上傳圖片
- Android實現(xiàn)上傳圖片至java服務(wù)器
- Android使用OkHttp上傳圖片的實例代碼
- Android 通過Base64上傳圖片到服務(wù)器實現(xiàn)實例
- Android開發(fā)中調(diào)用系統(tǒng)相冊上傳圖片到服務(wù)器OPPO等部分手機上出現(xiàn)短暫的顯示桌面問題的解決方法
- Android 開發(fā) 使用WebUploader解決安卓微信瀏覽器上傳圖片中遇到的bug
- 解決android有的手機拍照后上傳圖片被旋轉(zhuǎn)的問題
- Android使用post方式上傳圖片到服務(wù)器的方法
- Android Retrofit 2.0框架上傳圖片解決方案
- Android異步上傳圖片到PHP服務(wù)器
- android上傳圖片到PHP的過程詳解
- Android實現(xiàn)本地上傳圖片并設(shè)置為圓形頭像
- Android 使用騰訊X5瀏覽器上傳圖片的示例
相關(guān)文章
Android 動態(tài)顯示和隱藏狀態(tài)欄詳解及實例
這篇文章主要介紹了Android 動態(tài)顯示和隱藏狀態(tài)欄的相關(guān)資料,需要的朋友可以參考下2017-06-06
Android編程中FileOutputStream與openFileOutput()的區(qū)別分析
這篇文章主要介紹了Android編程中FileOutputStream與openFileOutput()的區(qū)別,結(jié)合實例形式分析了FileOutputStream與openFileOutput()的功能,使用技巧與用法區(qū)別,需要的朋友可以參考下2016-02-02
ERROR/AndroidRuntime(17121)的問題解決
ERROR/AndroidRuntime(17121)的問題解決,需要的朋友可以參考一下2013-05-05
Android源碼系列之深入理解ImageView的ScaleType屬性
Android源碼系列第一篇,這篇文章主要從源碼的角度深入理解ImageView的ScaleType屬性,感興趣的小伙伴們可以參考一下2016-06-06

