1.阿里云官方文档
2.拼接后的地址
http://image.chongdm.com/zhaozhuang/20200924/1600931173684.png
3.后台返回的数据格式必须解析如下:
接口:http://api.chongdm.com/gateway/oss/getOssToken
//正确返回
{
"StatusCode":200,
"AccessKeyId":"STS.3p***dgagdasdg",
"AccessKeySecret":"rpnwO9***tGdrddgsR2YrTtI",
"SecurityToken":"CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s˙∂˙∂3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVtbzI=",
"Expiration":"2017-12-12T07:49:09Z",
}
//错误返回
{
"StatusCode":500,
"ErrorCode":"InvalidAccessKeyId.NotFound",
"ErrorMessage":"Specified access key is not found."
}
3.app端上传文件路径,需要自己拼接
private var stsServer: String = "http://api.chongdm.com/gateway/oss/getOssToken"
private var oss: OSS? = null
fun initOSS() {
val credentialProvider: OSSCredentialProvider
credentialProvider = OSSAuthCredentialsProvider(stsServer)
val conf = ClientConfiguration()
conf.connectionTimeout = 15 * 1000 // 连接超时,默认15秒
conf.socketTimeout = 15 * 1000 // socket超时,默认15秒
conf.maxConcurrentRequest = 5 // 最大并发请求书,默认5个
conf.maxErrorRetry = 2 // 失败后最大重试次数,默认2次
oss = OSSClient(applicationContext, endpoint, credentialProvider, conf)
}
fun postToOss(path: String) {
val OssPath = "zhaozhuang/" + DateUtils.getCurrentDataDefaultString()+"/"+TimeUtils.getNowMills()+".png"
// 构造上传请求。
val put =
PutObjectRequest(bucketName, OssPath, path)
// 异步上传时可以设置进度回调。
put.progressCallback = OSSProgressCallback { request, currentSize, totalSize ->
Log.d(
"PutObject",
"currentSize: $currentSize totalSize: $totalSize"
)
}
val task: OSSAsyncTask<*> = oss!!.asyncPutObject(
put,
object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
override fun onSuccess(
request: PutObjectRequest?,
result: PutObjectResult
) {
Log.d("PutObject", "UploadSuccess")
Log.d("ETag", result.eTag)
Log.d("RequestId", result.toString())
}
override fun onFailure(
request: PutObjectRequest?,
clientExcepion: ClientException,
serviceException: ServiceException
) {
// 请求异常。
clientExcepion?.printStackTrace()
if (serviceException != null) {
// 服务异常。
Log.e("ErrorCode", serviceException.errorCode)
Log.e("RequestId", serviceException.requestId)
Log.e("HostId", serviceException.hostId)
Log.e("RawMessage", serviceException.rawMessage)
}
}
})
}