Android OSS上传图片到阿里云
我所采取的上传方式为异步上传,如果需要多张图片的话,可以直接循环上传就可以。
官方文档:https://help.aliyun.com/document_detail/93939.html?spm=a2c4g.11186623.6.1053.71a2bdce5HlAsk
依赖配置:(如果sdk依赖不同的话,部分类会出现导包失败的现象)
implementation'com.aliyun.dpa:oss-android-sdk:+'
implementation'com.squareup.okhttp3:okhttp:3.4.1'
implementation'com.squareup.okio:okio:1.9.0'
清单文件中所需要的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
混淆设置:
-keepclasscom.alibaba.sdk.android.oss.** {*; }
-dontwarn okio.**
-dontwarn org.apache.commons.codec.binary.**
工具类(这个工具类不涉及其他工具类,如果有导入错误现象,就查询配置的依赖是否有更新之类):
package lib.common.utils;
import android.content.Context;
import android.util.Log;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.OSSResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import java.text.SimpleDateFormat;
import java.util.Date;
import static okhttp3.internal.Internal.instance;
public class MyOSSUtils {
private static MyOSSUtilsinstance;
/**
* 主机地址(根据地区而变化)
*/
private final StringP_ENDPOINT ="https://oss-cn-beijing.aliyuncs.com";
/**
* (服务器域名,后台给)
*/
private final StringP_STSSERVER ="";
private final StringP_BUCKETNAME ="course-client";
private OSSoss;
private SimpleDateFormatsimpleDateFormat;
/**
* (文件夹名字,与后台统一)
*/
private final StringOBJECT_NAME ="";
public MyOSSUtils() {
}
public static MyOSSUtilsgetInstance() {
if (instance ==null) {
if (instance ==null) {
return new MyOSSUtils();
}
}
return instance;
}
private void getOSs(Context context) {
//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
OSSCredentialProvider credentialProvider =new OSSAuthCredentialsProvider(P_STSSERVER);
//该配置类如果不设置,会有默认配置,具体可看该类
ClientConfiguration conf =new ClientConfiguration();
conf.setConnectionTimeout(15 *1000);// 连接超时,默认15秒
conf.setSocketTimeout(15 *1000);// socket超时,默认15秒
conf.setMaxConcurrentRequest(5);// 最大并发请求数,默认5个
conf.setMaxErrorRetry(2);// 失败后最大重试次数,默认2次
oss =new OSSClient(context, P_ENDPOINT, credentialProvider);
if (simpleDateFormat ==null) {
simpleDateFormat =new SimpleDateFormat("yyyyMMdd");
}
}
/**
* 上传图片 上传文件
*
* @param context application上下文对象
* @param ossUpCallback 成功的回调
* @param img_name 上传到oss后的文件名称,图片要记得带后缀 如:.jpg
* @param imgPath 图片的本地路径
*/
public void upImage(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final Stringimg_name, String imgPath) {
getOSs(context);
// final Date data = new Date();
//
// data.setTime(System.currentTimeMillis());
PutObjectRequest putObjectRequest =new PutObjectRequest(P_BUCKETNAME, OBJECT_NAME +"/" + img_name, imgPath);
// 异步上传时可以设置进度回调。
putObjectRequest.setProgressCallback(new OSSProgressCallback() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
Log.d("PutObject", "currentSize: " + currentSize +" totalSize: " + totalSize);
}
});
OSSAsyncTask task =oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("PutObject", "UploadSuccess");
Log.d("ETag", result.getETag());
Log.d("RequestId", result.getRequestId());
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// 请求异常。
if (clientExcepion !=null) {
// 本地异常,如网络异常等。
clientExcepion.printStackTrace();
}
if (serviceException !=null) {
// 服务异常。
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback() {
@Override
public void onSuccess(OSSRequest request, OSSResult result) {
Log.e("MyOSSUtils", "------getRequestId:" + result.getRequestId());
ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME, OBJECT_NAME +"/" +img_name));
}
@Override
public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
ossUpCallback.successImg(null);
}
});
}
/**
* 上传图片 上传流
*
* @param context application上下文对象
* @param ossUpCallback 成功的回调
* @param img_name 上传到oss后的文件名称,图片要记得带后缀 如:.jpg
* @param imgbyte 图片的byte数组
*/
public void upImage(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final Stringimg_name, byte[] imgbyte) {
getOSs(context);
final Date data =new Date();
data.setTime(System.currentTimeMillis());
PutObjectRequest putObjectRequest =new PutObjectRequest(P_BUCKETNAME, simpleDateFormat.format(data) +"/" + img_name, imgbyte);
putObjectRequest.setProgressCallback(new OSSProgressCallback() {
@Override
public void onProgress(Object request, long currentSize, long totalSize) {
ossUpCallback.inProgress(currentSize, totalSize);
}
});
oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback() {
@Override
public void onSuccess(OSSRequest request, OSSResult result) {
Log.e("MyOSSUtils", "------getRequestId:" + result.getRequestId());
ossUpCallback.successImg(oss.presignPublicObjectURL(P_BUCKETNAME, simpleDateFormat.format(data) +"/" +img_name));
}
@Override
public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
ossUpCallback.successImg(null);
}
});
}
/**
* 上传视频
*
* @param context application上下文对象
* @param ossUpCallback 成功的回调
* @param video_name 上传到oss后的文件名称,视频要记得带后缀 如:.mp4
* @param video_path 视频的本地路径
*/
public void upVideo(Context context, final MyOSSUtils.OssUpCallback ossUpCallback, final Stringvideo_name, Stringvideo_path) {
getOSs(context);
final Date data =new Date();
data.setTime(System.currentTimeMillis());
PutObjectRequest putObjectRequest =new PutObjectRequest(P_BUCKETNAME, simpleDateFormat.format(data) +"/" + video_name, video_path);
putObjectRequest.setProgressCallback(new OSSProgressCallback() {
@Override
public void onProgress(Object request, long currentSize, long totalSize) {
ossUpCallback.inProgress(currentSize, totalSize);
}
});
oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback() {
@Override
public void onSuccess(OSSRequest request, OSSResult result) {
ossUpCallback.successVideo(oss.presignPublicObjectURL(P_BUCKETNAME, simpleDateFormat.format(data) +"/" +video_name));
}
@Override
public void onFailure(OSSRequest request, ClientException clientException, ServiceException serviceException) {
ossUpCallback.successVideo(null);
}
});
}
public interface OssUpCallback {
void successImg(Stringimg_url);
void successVideo(Stringvideo_url);
void inProgress(long progress, long zong);
}
}
调用方式:
参数携带具体根据与后台协商所定
//上传到阿里云
MyOSSUtils.getInstance().upImage(this, object : MyOSSUtils.OssUpCallback {
override fun successImg(img_url: String?) {
//在上传阿里云成功的回调中 在=将阿里云返回的url地址上传给后台即可
}
override fun successVideo(video_url: String?) {
}
override fun inProgress(progress: Long, zong: Long) {
}
}, “” +".jpg", cropImagePath)
备注:我上传时用到的地方就这么多,如果有问题,或者报异常直接可以在官网里根据所报异常去查询
调用方式使用的是kotlin代码,用的就是工具类里面的方法回调,就OK了。