阿里平台申请这几个参数
public static final String ACCESS_ID = "LTxxxxx"; //阿里云ID
public static final String ACCESS_KEY = "iMhzxxxxx"; //阿里云KEY
public static final String ACCESS_BUCKET_NAME = "qxjtuxxxxxxx";
public static final String ACCESS_ENDPOINT = "http://xxxxx";
public static final String ACCESS_DOMAINNAME = "http:xxxxx";
导入maven库
implementation 'com.aliyun.dpa:oss-android-sdk:2.9.13'
工具类HashUtil.java
public class HashUtil {
private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
private static String convertToHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (byte a : b) {
sb.append(HEX_DIGITS[(a & 0xf0) >>> 4]);
sb.append(HEX_DIGITS[a & 0x0f]);
}
return sb.toString();
}
/**
* Get a String's HashCode
*
* @param str String
* @return HashCode
*/
public static String getMD5String(String str) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md5.update(str.getBytes());
return convertToHexString(md5.digest());
}
/**
* Get a File's HashCode
*
* @param file File
* @return HashCode
*/
public static String getMD5String(File file) {
// Create md5
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
// Stream
InputStream in = null;
byte[] buffer = new byte[1024];
int numRead;
// Read
try {
in = new FileInputStream(file);
while ((numRead = in.read(buffer)) > 0) {
md5.update(buffer, 0, numRead);
}
return convertToHexString(md5.digest());
} catch (Exception e) {
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
上传文件管理类
public class ALiUploadManager {
private OSSClient ossClient = null;
private static ALiUploadManager instance = null;
public static ALiUploadManager getInstance() {
if (instance == null) {
synchronized (ALiUploadManager.class) {
if (instance == null) {
instance = new ALiUploadManager();
}
}
}
return instance;
}
/**
* 初始化阿里云SDK
*
* @param context
*/
public void init(Context context) {
OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(AppConstant.ACCESS_ID, AppConstant.ACCESS_KEY);
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
conf.setMaxConcurrentRequest(8); // 最大并发请求数,默认5个
conf.setMaxErrorRetry(3); // 失败后最大重试次数,默认2次
// oss为全局变量,OSS_ENDPOINT是一个OSS区域地址
ossClient = new OSSClient(context, AppConstant.ACCESS_ENDPOINT, credentialProvider, conf);
}
/**
* 上传图片到阿里云
*
* @param filePath 本地图片地址
*/
public OSSAsyncTask uploadFile(String filePath, final ALiCallBack callBack) {
// 构造上传请求
final String key = getObjectPortraitKey(filePath);
ILog.e("key:" + key);
PutObjectRequest put = new PutObjectRequest(AppConstant.ACCESS_BUCKET_NAME, key, filePath);
// 异步上传时可以设置进度回调
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
if (callBack != null) {
callBack.process(currentSize, totalSize);
}
}
});
final OSSAsyncTask task = ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
if (callBack != null) {
//获取可访问的url
String url = ossClient.presignPublicObjectURL(AppConstant.ACCESS_BUCKET_NAME, key);
callBack.onSuccess(request, result, url);
}
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// 请求异常
if (clientExcepion != null) {
// 本地异常如网络异常等
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// 服务异常
ILog.e("ErrorCode" + serviceException.getErrorCode());
ILog.e("RequestId" + serviceException.getRequestId());
ILog.e("HostId" + serviceException.getHostId());
ILog.e("RawMessage" + serviceException.getRawMessage());
}
if (callBack != null) {
callBack.onError(request, clientExcepion, serviceException);
}
}
});
return task;
}
//格式: portrait/201805/sfdsgfsdvsdfdsfs.jpg
private static String getObjectPortraitKey(String path) {
String fileMd5 = HashUtil.getMD5String(new File(path));
String dateString = getDateString();
return String.format("portrait/%s/%s.jpg", dateString, fileMd5);
}
/**
* 获取时间
*
* @return 时间戳 例如:201805
*/
private static String getDateString() {
return DateFormat.format("yyyyMM", new Date()).toString();
}
public interface ALiCallBack {
/**
* 上传成功
*
* @param request
* @param result
*/
void onSuccess(PutObjectRequest request, PutObjectResult result, String url);
/**
* 上传失败
*
* @param request
* @param clientExcepion
* @param serviceException
*/
void onError(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException);
/**
* 上传进度
*
* @param currentSize 当前进度
* @param totalSize 总进度
*/
void process(long currentSize, long totalSize);
}
}
外部如何使用
ALiUploadManager.getInstance().uploadFile(path, new ALiUploadManager.ALiCallBack() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result, String url) {
ILog.e("上传阿里云成功:" + url);
putImage(url); //路径回调至服务端
}
@Override
public void onError(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
ILog.e("上传阿里云失败clientExcepion:" + clientExcepion.getMessage() + ",serviceException:" + serviceException);
ToastUtil.showShortToast(ImageSubmitActivity.this, "上传失败");
}
@Override
public void process(long currentSize, long totalSize) {
ILog.e("上传中:" + (currentSize * 100) / totalSize + "%");
}
});