Android Oss上傳圖片的使用示例
前言
前一陣項(xiàng)目中的上傳圖片改為上傳到阿里上,記錄一下實(shí)現(xiàn)的過(guò)程,方便以后查看。
參考資料:官方文檔
配置
Android studio添加依賴(lài)
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包(對(duì)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 個(gè) jar 包導(dǎo)入 libs 目錄
權(quán)限設(shè)置
確保AndroidManifest.xml 文件中已經(jīng)配置了這些權(quán)限,否則,SDK 將無(wú)法正常工作。
<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.**
實(shí)現(xiàn)過(guò)程
首先為了安全起見(jiàn),采用的是STS鑒權(quán)模式,則要用到的數(shù)據(jù)都是從后臺(tái)獲得然后應(yīng)用到前臺(tái)的。
1.創(chuàng)建OSSClient (自己在這里命名為OssService)
OSSClient為OSS 服務(wù)的 Android 客戶(hù)端,它為調(diào)用者提供了一系列的方法,可以用來(lái)操作,管理存儲(chǔ)空間(bucket)和文件(object)等。
public class OssService {
private OSS oss;
private String bucket;
private picResultCallback callback;//回調(diào)接口
private String path=地址(后臺(tái)告訴);
public OssService(OSS oss, String bucket,picResultCallback callback) {
this.oss = oss;
this.bucket = bucket;
this.callback=callback;
}
/**object字段為圖片的上傳地址(具體地址的前綴后端給,這個(gè)是拼起
*來(lái)的一個(gè)路徑)
*localFile圖片的本地地址
*mProgress 進(jìn)度條
*img 顯示圖片的控件
*type 類(lèi)型
*/
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)造上傳請(qǐng)求
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í)可以設(shè)置進(jìn)度回調(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 = "";
// 請(qǐng)求異常
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.實(shí)現(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); // 連接超時(shí),默認(rèn)15秒
conf.setSocketTimeout(15 * 1000); // socket超時(shí),默認(rèn)15秒
conf.setMaxConcurrentRequest(5); // 最大并發(fā)請(qǐng)求書(shū),默認(rèn)5個(gè)
conf.setMaxErrorRetry(2); // 失敗后最大重試次數(shù),默認(rèn)2次
OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
return new OssService(oss, bucket, this);
}
3.重載OSSFederationCredentialProvider生成自己的獲取STS的功能(一般自動(dòng)獲得token寫(xiě)在這里,在getFederationToken()方法中,告訴它你獲得token的規(guī)則即可)
1>官方demo代碼(自動(dòng)更新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>自己的代碼(因?yàn)樽约旱乃袛?shù)據(jù)都是從后臺(tái)獲得的,而且結(jié)合rxjava沒(méi)有想到可以返回?cái)?shù)據(jù)的方式,所以采用手動(dòng)更新token的方式)
手動(dòng)更新token的具體操作:
首先token的值存在MyApp中,第一次在進(jìn)入需要用到token界面時(shí)候,先獲得token的值更新MyApp中的值并記錄當(dāng)下的時(shí)間,如果下次再次進(jìn)入任何一個(gè)需要用到token的界面的時(shí)候,則判斷時(shí)間是否過(guò)期,過(guò)期則重新請(qǐng)求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.實(shí)例化OSSClient,調(diào)用上傳圖片方法
//實(shí)例化OSSClient (自己是在onCreate()中實(shí)例化的,當(dāng)然考慮到token的過(guò)期問(wèn)題,也有在onResume()中再次實(shí)例化一次) ossService = initOSS(tokenBean.getBucket().getEndPoint(), tokenBean.getBucket().getBucketName()); //上傳圖片,需要根據(jù)自己的邏輯傳參數(shù) ossService.asyncPutImage(圖片在阿里上的存儲(chǔ)路徑, 本地路徑, ...);
5.回調(diào)處理圖片邏輯
/**
* 對(duì)圖片上傳回來(lái)的數(shù)據(jù)進(jìn)行處理
* @param data
*/
@Override
public void getPicData(PutObjectResult data, String oldPath) {
Gson gson = new Gson();
OssUploadImage uploadImage = gson.fromJson(data.getServerCallbackReturnBody(), OssUploadImage.class);
........邏輯自己寫(xiě)吧
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android基于OkHttp實(shí)現(xiàn)下載和上傳圖片
- Android實(shí)現(xiàn)上傳圖片至java服務(wù)器
- Android使用OkHttp上傳圖片的實(shí)例代碼
- Android 通過(guò)Base64上傳圖片到服務(wù)器實(shí)現(xiàn)實(shí)例
- Android開(kāi)發(fā)中調(diào)用系統(tǒng)相冊(cè)上傳圖片到服務(wù)器OPPO等部分手機(jī)上出現(xiàn)短暫的顯示桌面問(wèn)題的解決方法
- Android 開(kāi)發(fā) 使用WebUploader解決安卓微信瀏覽器上傳圖片中遇到的bug
- 解決android有的手機(jī)拍照后上傳圖片被旋轉(zhuǎn)的問(wèn)題
- Android使用post方式上傳圖片到服務(wù)器的方法
- Android Retrofit 2.0框架上傳圖片解決方案
- Android異步上傳圖片到PHP服務(wù)器
- android上傳圖片到PHP的過(guò)程詳解
- Android實(shí)現(xiàn)本地上傳圖片并設(shè)置為圓形頭像
- Android 使用騰訊X5瀏覽器上傳圖片的示例
相關(guān)文章
Android 跨進(jìn)程通Messenger(簡(jiǎn)單易懂)
這篇文章主要介紹了Android Messenger跨進(jìn)程通的相關(guān)資料,非常簡(jiǎn)單容易理解,對(duì)android messenger 進(jìn)程通訊的相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2016-08-08
Android 動(dòng)態(tài)顯示和隱藏狀態(tài)欄詳解及實(shí)例
這篇文章主要介紹了Android 動(dòng)態(tài)顯示和隱藏狀態(tài)欄的相關(guān)資料,需要的朋友可以參考下2017-06-06
Android打開(kāi)WebView黑屏閃爍問(wèn)題排查
這篇文章主要介紹了Android打開(kāi)WebView黑屏閃爍問(wèn)題排查,文章通過(guò)詳細(xì)的代碼示例和圖文介紹WebView黑屏閃爍的問(wèn)題,感興趣的小伙伴可以跟著小編一起來(lái)學(xué)習(xí)2023-05-05
Android編程中FileOutputStream與openFileOutput()的區(qū)別分析
這篇文章主要介紹了Android編程中FileOutputStream與openFileOutput()的區(qū)別,結(jié)合實(shí)例形式分析了FileOutputStream與openFileOutput()的功能,使用技巧與用法區(qū)別,需要的朋友可以參考下2016-02-02
ERROR/AndroidRuntime(17121)的問(wèn)題解決
ERROR/AndroidRuntime(17121)的問(wèn)題解決,需要的朋友可以參考一下2013-05-05
Android源碼系列之深入理解ImageView的ScaleType屬性
Android源碼系列第一篇,這篇文章主要從源碼的角度深入理解ImageView的ScaleType屬性,感興趣的小伙伴們可以參考一下2016-06-06
Android基于OpenCV實(shí)現(xiàn)霍夫直線(xiàn)檢測(cè)
霍夫變換利用點(diǎn)與線(xiàn)之間的對(duì)偶性,將圖像空間中直線(xiàn)上離散的像素點(diǎn)通過(guò)參數(shù)方程映射為霍夫空間中的曲線(xiàn),并將霍夫空間中多條曲線(xiàn)的交點(diǎn)作為直線(xiàn)方程的參數(shù)映射為圖像空間中的直線(xiàn)。給定直線(xiàn)的參數(shù)方程,可以利用霍夫變換來(lái)檢測(cè)圖像中的直線(xiàn)。本文簡(jiǎn)單講解Android的實(shí)現(xiàn)2021-06-06

