官方文档写的比较清楚,只是某些细节方面还是不是很明白,特此写下封装好的方法方便寻找
//上传图片到百度云
public static void upLoadPic(Context context, String url,String name,String photonum){
String endpoint ="https://oss-**************.com";
OSSCustomSignerCredentialProvider credentialProvider =new OSSCustomSignerCredentialProvider() {
@Override
public StringsignContent(String content) {
LogTools.logi(Contans.TAG,"content="+content+"-"+url);
try {//网络请求获取自签名串号
String run = Helper.run(Contans.URL +"/aliyun/oss/getPolicy?content=" + URLEncoder.encode(content, "UTF-8"));
LogTools.logi(Contans.TAG,"OSSCustomSignerCredentialProvider="+run);
Results results = JSON.parseObject(run, Results.class);
String data = results.getData();
return "OSS " +"accessKeyId "+":" + data;
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
OSS oss =new OSSClient(context.getApplicationContext(), endpoint, credentialProvider);
// 到此初始化完成
//接下来上传图片到oss。
PutObjectRequest put =new PutObjectRequest("<bucketName>", "存放oss的图片文件夹路径(基本不变)"+"文件名称(变化的图片名称)", "本地要上传的图片的路径及名称");
// 异步上传时可以设置进度回调。
put.setProgressCallback(new OSSProgressCallback() {
@Override
public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
Log.d(Contans.TAG, "currentSize: " + currentSize +" totalSize: " + totalSize);
}
});
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d(Contans.TAG, "UploadSuccess");
Log.d(Contans.TAG, result.getETag());
Log.d(Contans.TAG, result.getRequestId());
SharedPreferencesUtils.put(context,photonum,"oss链接路径(基本不变)"+"图片名称");//成功后存储返回的路径
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// 请求异常。
if (clientExcepion !=null) {
// 本地异常,如网络异常等。
clientExcepion.printStackTrace();
}
if (serviceException !=null) {
// 服务异常。
Log.e(Contans.TAG, serviceException.getErrorCode());
Log.e(Contans.TAG, serviceException.getRequestId());
Log.e(Contans.TAG, serviceException.getHostId());
Log.e(Contans.TAG, serviceException.getRawMessage());
}
}
});
}