public class OssServiceUtil {
private OSS oss;
private picResultCallback callback;//回调接口
public OssServiceUtil(String bucketname, String endpoint, OssData data) {
this.bucketname =bucketname;
this.endpoint = endpoint;
OssData cansh = data;
this.accessKeyId = cansh.getAccessKeyId();
this.securityToken = cansh.getSecurityToken();
this.accessKeySecret = cansh.getAccessKeySecret();
this.init();
}
//初始化使用参数
String accessKeyId,securityToken,accessKeySecret,endpoint,bucketname;
private void init() {
this.init(null);
}
private interface Cb {
void success();
void error();
}
private void init(Cb cb) {
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
//这个初始化安全性没有Sts安全,如需要很高安全性建议用OSSStsTokenCredentialProvider创建(上一行创建方式)多出的参数SecurityToken为临时授权参数
// OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
conf.setMaxConcurrentRequest(8); // 最大并发请求数,默认5个
conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
// oss为全局变量,endpoint是一个OSS区域地址
oss = new OSSClient(MyApplication.getInstance(), endpoint, credentialProvider, conf);
}
public void setResultCallBack(picResultCallback callback) {
this.callback = callback;
}
public void upload(final List<File> file){
if (oss == null) {
this.init(new Cb() {
@Override
public void success() {
up(file);
}
@Override
public void error() {
MyUtils.show("上传失败");
if (callback != null) {
callback.getPicData(null);
}
}
});
return;
}
up(file);
}
private void up(List<File> files) {
final int count = files.size();
final List<String> results = new ArrayList<String>(count);
final List<String> r = new ArrayList<String>();
for (File file : files) {
results.add("");
final int index = files.indexOf(file);
ObjectMetadata objectMeta = new ObjectMetadata();
objectMeta.setContentType("image/jpeg");
// 构造上传请求
// 这里的objectKey其实就是服务器上的路径,即目录+文件名
//因为目录命名逻辑涉及公司信息,被我删去,造成不知道这个objectKey不知为何物,如下是我们公司的大致命名逻辑
//String objectKey = keyPath + "/" + carArr[times] + ".jpg";
PutObjectRequest put = new PutObjectRequest(bucketname, file.getName(),file.getPath());
put.setMetadata(objectMeta);
try {
PutObjectResult putObjectResult = oss.putObject(put);
} catch (ClientException e) {
e.printStackTrace();
if (callback != null) {
callback.getPicData(null);
}
} catch (ServiceException e) {
e.printStackTrace();
if (callback != null) {
callback.getPicData(null);
}
}
// 异步上传时可以设置进度回调
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
// 在这里可以实现进度条展现功能
Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
}
});
oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("PutObject", "UploadSuccess");
Log.d("ETag", result.getETag());
Log.d("RequestId", result.getRequestId());
//上传后获取地址:
String prefix = "https://" + bucketname + "."+endpoint+ "/";
Log.d("prefix得值", prefix);
String fileUrl = prefix + request.getObjectKey();
results.set(index, fileUrl);
r.add("");
if (r.size() == count && callback != null) {
callback.getPicData(results);
}
}
@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());
}
MyUtils.show( "图片上传失败,请重新上传");
if (callback != null) {
callback.getPicData(null);
}
return;
}
});
}
}
public void upFile(final File file){
if (oss == null) {
this.init(new Cb() {
@Override
public void success() {
UploadFile(file);
}
@Override
public void error() {
MyUtils.show("上传失败");
if (callback != null) {
callback.getPicData(null);
}
}
});
return;
}
UploadFile(file);
}
public void UploadFile(File file) {
List<String> url=new ArrayList<>();
// credentialProvider = new OSSStsTokenCredentialProvider(AccessKeyId, SecretKeyId, SecurityToken);
// 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, endpoint, credentialProvider, conf);
// 构造上传请求。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketname, file.getName(), file.getPath());
// 异步上传时可以设置进度回调。
putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
}
});
OSSAsyncTask ossAsyncTask = oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
url.clear();
url.add(oss.presignPublicObjectURL(bucketname,file.getName()));
callback.getPicData(url);
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// 请求异常。
if (clientExcepion != null) {
// 本地异常,如网络异常等。
clientExcepion.printStackTrace();
MyUtils.show("网络异常");
}
if (serviceException != null) {
// 服务异常。
MyUtils.show("服务异常");
}
}
});
// ossAsyncTask.cancel(); // 可以取消任务
// ossAsyncTask.waitUntilFinished(); // 等待任务完成
}
public interface picResultCallback {
void getPicData(List<String> path);
}
}
使用时 getBucket getEndpoint 都是后台返回的
ossServiceUtil = new OssServiceUtil(data.getBucket(), data.getEndpoint(), data);
ossServiceUtil.setResultCallBack(new OssServiceUtil.picResultCallback() {
@Override
public void getPicData(List<String> path) {
if (path != null && path.size() != 0) {
//返回的地址回调
}
}
});
ossServiceUtil.upFile(mAudioFile);
|