package com.yazq.hszm.utils;
import android.content.Context;
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.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.CompleteMultipartUploadResult;
import com.alibaba.sdk.android.oss.model.MultipartUploadRequest;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.utils.Log;
import com.yazq.hszm.network.ServerUrl;
public class OssService {
private OSS oss;
private String accessKeyId;
private String bucketName;
private String accessKeySecret;
private String endpoint;
private Context context;
private ProgressCallback progressCallback;
private ProgressCallback1 progressCallback1;
private int type;
public OssService(Context context, String accessKeyId, String accessKeySecret, String endpoint, String bucketName, int i) {
this.context = context;
this.endpoint = endpoint;
this.bucketName = bucketName;
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.type = i;
}
public void asyncMultipartUpload(String uploadKey, String uploadFilePath) {
MultipartUploadRequest request = new MultipartUploadRequest(bucketName, uploadKey, uploadFilePath);
request.setCRC64(OSSRequest.CRC64Config.YES);
request.setProgressCallback(new OSSProgressCallback<MultipartUploadRequest>() {
@Override
public void onProgress(MultipartUploadRequest request, long currentSize, long totalSize) {
OSSLog.logDebug("[testMultipartUpload] - " + currentSize + " " + totalSize, false);
int progress = (int) (100 * currentSize / totalSize);
android.util.Log.e("OSS=======", "onProgress: " + progress);
// mDisplayer.updateProgress(progress);
// mDisplayer.displayInfo("上传进度: " + String.valueOf(progress) + "%");
}
});
oss.asyncMultipartUpload(request, new OSSCompletedCallback<MultipartUploadRequest, CompleteMultipartUploadResult>() {
@Override
public void onSuccess(MultipartUploadRequest request, CompleteMultipartUploadResult result) {
// mDisplayer.uploadComplete();
android.util.Log.e("OSS=======", "onSuccess: " + new Gson().toJson(request.toString()));
// mDisplayer.displayInfo(request.toString());
}
@Override
public void onFailure(MultipartUploadRequest request, ClientException clientException, ServiceException serviceException) {
if (clientException != null) {
android.util.Log.e("OSS=======", "clientException: " + new Gson().toJson(clientException.toString()));
// mDisplayer.displayInfo(clientException.toString());
} else if (serviceException != null) {
android.util.Log.e("OSS=======", "serviceException: " + new Gson().toJson(serviceException.toString()));
// mDisplayer.displayInfo(serviceException.toString());
}
}
});
}
public void setii(String localFilepath) {
// 填写Bucket名称,例如examplebucket。
String bucketName = ServerUrl.red_dream;
// 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
String objectName = FileUtils.getfilename("", "");
// 填写本地文件完整路径,例如/storage/emulated/0/oss/examplefile.txt。
// String localFilepath = "/storage/emulated/0/oss/examplefile.txt";
ObjectMetadata meta = new ObjectMetadata();
// 设置文件元信息等。
meta.setHeader("x-oss-object-acl", "public-read-write");
MultipartUploadRequest rq = new MultipartUploadRequest(bucketName, objectName, localFilepath, meta);
// 设置PartSize。PartSize默认值为256 KB,最小值为100 KB。
rq.setPartSize(1024 * 1024);
rq.setProgressCallback(new OSSProgressCallback<MultipartUploadRequest>() {
@Override
public void onProgress(MultipartUploadRequest request, long currentSize, long totalSize) {
OSSLog.logDebug("[testMultipartUpload] - " + currentSize + " " + totalSize, false);
}
});
try {
CompleteMultipartUploadResult result = oss.multipartUpload(rq);
if (progressCallback1 != null) {
progressCallback1.onProgressonSuccessCallback(result, type);
}
android.util.Log.e("=========", "setii: " + result.getObjectKey() + "");
} catch (ClientException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
public void initOSSClient() {
//OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.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(context, endpoint, credentialProvider, conf);
}
public void beginupload(Context context, String filename, String path) {
//通过填写文件名形成objectname,通过这个名字指定上传和下载的文件
String objectname = filename;
if (objectname == null || objectname.equals("")) {
// ToastUtils.showShort("文件名不能为空");
return;
}
//下面3个参数依次为bucket名,Object名,上传文件路径
PutObjectRequest put = new PutObjectRequest(bucketName, objectname, path);
if (path == null || path.equals("")) {
// LogUtil.d("请选择图片....");
//ToastUtils.showShort("请选择图片....");
return;
}
Log.i("ccc", "正在上传中....");
//ToastUtils.showShort("正在上传中....");
// 异步上传,可以设置进度回调
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
android.util.Log.e("oss", "onProgress: ");
//LogUtil.d("currentSize: " + currentSize + " totalSize: " + totalSize);
double progress = currentSize * 1.0 / totalSize * 100.f;
android.util.Log.e("oss", "onProgress: " + progress);
if (progressCallback != null) {
progressCallback.onProgressCallback(progress);
}
}
});
@SuppressWarnings("rawtypes")
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
android.util.Log.e("oss", "onSuccess: ");
if (progressCallback != null) {
progressCallback.onProgressonSuccessCallback(request, result,type);
}
//ToastUtils.showShort("上传成功");
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
android.util.Log.e("oss", "onFailure: ");
// 请求异常
/// LogUtil.d("UploadFailure");
// ToastUtils.showShort("UploadFailure");
if (clientExcepion != null) {
// 本地异常如网络异常等
Log.i("sss", "UploadFailure:表示向OSS发送请求或解析来自OSS的响应时发生错误。\n" + " *例如,当网络不可用时,这个异常将被抛出");
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// 服务异常
Log.i("sss", "UploadFailure:表示在OSS服务端发生错误");
Log.i("sss", serviceException.getErrorCode());
Log.i("sss", serviceException.getRequestId());
Log.i("sss", serviceException.getHostId());
Log.i("sss", serviceException.getRawMessage());
}
}
});
//task.cancel(); // 可以取消任务
//task.waitUntilFinished(); // 可以等待直到任务完成
}
public ProgressCallback getProgressCallback() {
return progressCallback;
}
public ProgressCallback1 getProgressCallback1() {
return progressCallback1;
}
public void setProgressCallback1(ProgressCallback1 progressCallback1) {
this.progressCallback1 = progressCallback1;
}
public void setProgressCallback(ProgressCallback progressCallback) {
this.progressCallback = progressCallback;
}
public interface ProgressCallback {
void onProgressCallback(double progress);
void onProgressonSuccessCallback(PutObjectRequest request, PutObjectResult result,int type);
}
public interface ProgressCallback1 {
void onProgressCallback(double progress);
void onProgressonSuccessCallback(CompleteMultipartUploadResult completeMultipartUploadResult, int id);
}
}
|