阿里雲OSS對象存儲OSS文件上傳
5 人贊了文章
先來張圖哈:
最近工作做了一個項目有個功能用到阿里雲OSS對象存儲OSS分享出來給大家!!!其實不難很容易,看著官方文檔做就好了!不多說直接上代碼;
1、OSSUtils.class(工具類)
public class OSSUtils{public Context context; //設置OSS數據中心域名或者cname域名 private static String host_id = "oss-cn-shenzhen.aliyuncs.com"; //Key private static String access = "";//私鑰 private static String secret = "";//服務端秘鑰 //OSS的Bucket private static String bucket = "";//就叫存儲空間名吧 private static String object = "";//存放路徑 private static String folder;//路徑文件夾 private static String token = "";//token public static OSS oss; public OSSUtils() { }/** * 初始化並配置 * @param context * @param bean * @return */ public static OSS init(Context context, DataBean bean) { //把配置數據傳進來 setAccess(bean.getAccess()); setSecret(bean.getSecret()); setToken(bean.getToken()); setBucket(bean.getBucket()); setObject(bean.getObject()); setFolder(bean.getFolder()); OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(access, secret, token); ClientConfiguration conf = new ClientConfiguration(); conf.setConnectionTimeout(15 * 1000); // 連接超時,默認15秒 conf.setSocketTimeout(15 * 1000); // socket超時,默認15秒 conf.setMaxConcurrentRequest(9); // 最大並發請求書,默認5個 conf.setMaxErrorRetry(2); // 失敗後最大重試次數,默認2次 oss = new OSSClient(context, host_id, credentialProvider, conf); LogUtils.d("OSS初始化成功"); return oss; }/** * 文件上傳中 * * @param objectKey Oss保存路徑 * @param uploadFilePath 上傳文件本地路徑 * @return */ public static PutObjectRequest getPut(String objectKey, final String uploadFilePath) { PutObjectRequest put = new PutObjectRequest(bucket, folder + "/" + objectKey, uploadFilePath); put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {@Override public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {//上傳進度監聽Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize); } }); return put; }public Context getContext() {return context; }public void setContext(Context context) {this.context = context; }public static String getHost_id() {return host_id; }public static void setHost_id(String host_id) { OSSUtils.host_id = host_id; }public static String getAccess() {return access; }public static void setAccess(String access) { OSSUtils.access = access; }public static String getSecret() {return secret; }public static void setSecret(String secret) { OSSUtils.secret = secret; }public static String getBucket() {return bucket; }public static void setBucket(String bucket) { OSSUtils.bucket = bucket; }public static String getObject() {return object; }public static void setObject(String object) { OSSUtils.object = object; }public static String getFolder() {return folder; }public static void setFolder(String folder) { OSSUtils.folder = folder; }public static String getToken() {return token; }public static void setToken(String token) { OSSUtils.token = token; }public static OSS getOss() {return oss; }public static void setOss(OSS oss) { OSSUtils.oss = oss; }}2、DataBean.class(配置數據)public class DataBean { //設置OSS數據中心域名或者cname域名 private String host_id = "oss-cn-shenzhen.aliyuncs.com"; //Key private String access = "";//私鑰 private String secret = "";//服務端秘鑰 //OSS的Bucket private String bucket = "";//就叫存儲空間名吧 private String object = "";//存放路徑 private String folder;//路徑文件夾 private String token = "";//token public String getHost_id() { return host_id; } public void setHost_id(String host_id) { this.host_id = host_id; } public String getAccess() { return access; } public void setAccess(String access) { this.access = access; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public String getObject() { return object; } public void setObject(String object) { this.object = object; } public String getFolder() { return folder; } public void setFolder(String folder) { this.folder = folder; } public String getToken() { return token; } public void setToken(String token) { this.token = token; }}3、PostFileCallBack.class(上傳成功回調)public class PostFileCallBack implements OSSCompletedCallback<PutObjectRequest, PutObjectResult> { @Override public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) { LogUtils.d("上傳成功ObjectKey:" + putObjectRequest.getObjectKey()); onFileCallBack(putObjectRequest.getObjectKey(),200); } //code 200上傳成功 500失敗 public void onFileCallBack(String objectKey,int code) { } @Override public void onFailure(PutObjectRequest putObjectRequest, ClientException clientExcepion, ServiceException serviceException) { // 請求異常 if (clientExcepion != null) { // 本地異常如網路異常等 clientExcepion.printStackTrace(); } if (serviceException != null) { // 服務異常 LogUtils.e("ErrorCode:" + serviceException.getErrorCode()); LogUtils.e("RequestId:" + serviceException.getRequestId()); LogUtils.e("HostId:" + serviceException.getHostId()); LogUtils.e("RawMessage:" + serviceException.getRawMessage()); } onFileCallBack("",500); }}4、OssTimer.class 計時器public class OssTimer extends CountDownTimer { //傳入值到計時 public OssTimer(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } //直接寫死 public OssTimer() { super(14*60*1000, 1000); } @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { //時間到了就清空他唄 OSSUtils.oss=null; }}5、初始化用法DataBean = (DataBean) bean; OSSUtils.init(getActivity(), DataBean); //配置請求成功就開始到計時 OssTimer ossTimer = new OssTimer(); ossTimer.start();6、上傳:if (OSSUtils.getOss() == null) { //調 5 } else { chooseImage(); }pubilc void chooseImage(String file){ new Thread(new Runnable() { @Override public void run() { OSSUtils.getOss().asyncPutObject(OSSUtils.getPut(imageUrl, filePath),new PostFileCallBack() { @Override public void onFileCallBack(String objectKey, int code) { super.onFileCallBack(objectKey, code); fileUrl = "http://" + OSSUtils.getBucket() + "." + OSSUtils.getOssHostId() + "/" + objectKey;//拼接路徑 LogUtils.d("fileUrl:" + fileUrl);//列印上傳成功後的路徑 handler.sendEmptyMessage(code);//發消息去刷新 } }); } }).start();}public Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 200) { ToastUtils.toast("上傳成功"); } else { ToastUtils.toast("上傳失敗"); } super.handleMessage(msg); } };
推薦閱讀:
※ASP.NET MVC文件上傳、文件拖拽上傳demo
※可以直接html5標籤multiple多input多文件、單input多文件上傳.
※Asp.net 文件上傳的 FileUpload FileName 和 FileUpload PostedFile.FileName的細節問題