【移動(dòng)應(yīng)用開發(fā)技術(shù)】怎么在Android中利用Oss上傳圖片_第1頁
【移動(dòng)應(yīng)用開發(fā)技術(shù)】怎么在Android中利用Oss上傳圖片_第2頁
【移動(dòng)應(yīng)用開發(fā)技術(shù)】怎么在Android中利用Oss上傳圖片_第3頁
【移動(dòng)應(yīng)用開發(fā)技術(shù)】怎么在Android中利用Oss上傳圖片_第4頁
【移動(dòng)應(yīng)用開發(fā)技術(shù)】怎么在Android中利用Oss上傳圖片_第5頁
已閱讀5頁,還剩4頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

【移動(dòng)應(yīng)用開發(fā)技術(shù)】怎么在Android中利用Oss上傳圖片

這篇文章給大家介紹怎么在Android中利用Oss上傳圖片,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。Androidstudio添加依賴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ì)Androidstudio或者Eclipse都適用)1.在官網(wǎng)下載sdk包2.解壓后得到j(luò)ar包,目前包括aliyun-oss-sdk-android-x.x.x.jar、okhttp-3.x.x.jar和okio-1.x.x.jar3.將以上3個(gè)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

mons.codec.binary.**實(shí)現(xiàn)過程首先為了安全起見,采用的是STS鑒權(quán)模式,則要用到的數(shù)據(jù)都是從后臺(tái)獲得然后應(yīng)用到前臺(tái)的。1.創(chuàng)建OSSClient(自己在這里命名為OssService)OSSClient為OSS服務(wù)的Android客戶端,它為調(diào)用者提供了一系列的方法,可以用來操作,管理存儲(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è)是拼起

*來的一個(gè)路徑)

*localFile圖片的本地地址

*mProgress

進(jìn)度條

*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)造上傳請(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}");

///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)求書,默認(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寫在這里,在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沒有想到可以返回?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í)間是否過期,過期則重新請(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().getS

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論