阿里云OSS 上传文件

阿里云后台管理、API 集成教程、Key/ 域名的查询


1、查看上传的文件在哪?

a 、百度阿里云,进入官网。然后进入管理控制台

阿里云OSS 上传文件_第1张图片


b、左侧菜单栏,进入对象存储 OSS 

阿里云OSS 上传文件_第2张图片


c、进入 Bucket 管理页面,点击创建的bucket 名称

阿里云OSS 上传文件_第3张图片


d、进入bucket 管理界面,点击左侧菜单

bucket属性 菜单查看bucket 域名

object 管理  查看管理上传的文件

图片处理   查看图片域名地址

阿里云OSS 上传文件_第4张图片


阿里云OSS 上传文件_第5张图片


阿里云OSS 上传文件_第6张图片


2、查看accessKey  和 screctKey 

阿里云OSS 上传文件_第7张图片


阿里云OSS 上传文件_第8张图片

3、集成 OSS  sdk下载地址和API  地址

https://help.aliyun.com/document_detail/oss/sdk/android-sdk/preface.html?spm=5176.docoss/api-reference/abstract.6.302.9Lrnuz



Android 实现上传图片


1、下载sdk    https://help.aliyun.com/document_detail/oss/sdk/android-sdk/preface.html?spm=5176.docoss/sdk/android-sdk/get-start.6.302.WewVmT

  • 解压后得到 jar 包,目前包括 aliyun-oss-sdk-android-2.2.0.jar、okhttp-3.2.0.jar 和 okio-1.6.0.jar
  • 将以上 3 个 jar 包导入 libs 目录
2、在android manifest中增加权限




3、初始化 OSS client 
可以建个 application  在 application中初始化,记得修改android manifest 中 application  name 

4、实现上传功能

代码:
application:
package com.tan.uploadtooss;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
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 android.app.Application;
import android.app.usage.NetworkStats.Bucket;

public class MainApplication extends Application {
	
	//OSS的Bucket
	public static final String OSS_BUCKET = Bucket名称;
	//设置OSS数据中心域名或者cname域名
	public static final String OSS_BUCKET_HOST_ID = 域名,不包含bucket;
	//Key
	private static final String accessKey = accessKey;
	private static final String screctKey = screctKey;
	
	public static OSS oss;
	@Override
	public void onCreate() {
		super.onCreate();
		//初始化OSS配置
		initOSSConfig();
	}
	
	private void initOSSConfig(){
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKey, screctKey);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
        if(BuildConfig.DEBUG){
        	OSSLog.enableLog();
        }
        oss = new OSSClient(getApplicationContext(), MainApplication.OSS_BUCKET_HOST_ID, credentialProvider, conf);
	}
	
	
}

activity:
package com.tan.uploadtooss;

import java.text.SimpleDateFormat;
import java.util.Date;
import com.alibaba.sdk.android.oss.ClientException;
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.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private String mUploadFilePath = "/storage/emulated/0/DCIM/Camera/IMG_20150701_104558.jpg";
	private Button vCommit;
	
	protected Handler mHandler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		vCommit = (Button) findViewById(R.id.btn_commit);
		vCommit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				uploadData( mUploadFilePath);
			}
		});
	}
	

	/**
	 * 上传图片
	 * @param imageByte
	 */
	private void uploadData(String uploadFilePath){
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				//显示个等待页面
			}
		});
		
		PutObjectRequest put = new PutObjectRequest(MainApplication.OSS_BUCKET, "image/albums/"+getImageObjectKey("123456789"), uploadFilePath);
			
		put.setProgressCallback(new OSSProgressCallback() {
			@Override
			public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
				 Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
			}
		});
			
		MainApplication.oss.asyncPutObject(put, new OSSCompletedCallback() {
			@Override
			public void onSuccess(final PutObjectRequest request, PutObjectResult result) {
				Log.d("PutObject", "UploadSuccess");
	            Log.d("ETag", result.getETag());
	            Log.d("RequestId", result.getRequestId());
	            //将上传成功的图片地址传给自己的服务器后台,比如修改用户数据库中,用户头像的url。
	            //修改后台url成功后,再利用glide 下载最新的照片,修改本地头像图片。
	            //request.getObjectKey() 是图片地址,但是不包含,OSS 图片域名
//	            uploadImage(request.getObjectKey());
			}
				
			@Override
			public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							//如果上传失败了,通过mHandler ,发出失败的消息到主线程中。处理异常。
//							showNetErrorInfo();
						}
					});
				       // 请求异常
	               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());
	               }
					
			}
		});
			
	}
	
	//通过UserCode 加上日期组装 OSS路径
	private String getImageObjectKey (String strUserCode){
		
    	Date date = new Date();
    	return new SimpleDateFormat("yyyy/M/d").format(date)+"/"+strUserCode+new SimpleDateFormat("yyyyMMddssSSS").format(date)+".jpg";
		    
	}
	
	
	
}

//将上传成功的图片地址传给自己的服务器后台,比如修改用户数据库中,用户头像的url。
//修改后台url成功后,再利用glide 下载最新的照片,修改本地头像图片。
//request.getObjectKey() 是图片地址,但是不包含,OSS 图片域名

实现代码:

/**
	 * 上传图片地址到接口后台
	 * @param string
	 */
	protected void uploadImage(final String faceImg) {
		String url = HttpHelper.HTTP_URL+HttpHelper.UserUrl.MODIFY_MEMBER;
		Map map = new HashMap();
		map.put("faceImg", faceImg);
		Map params = new HashMap();
		params = Utils.getParams(map, mContext);
		
		StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener() {
			@Override
			public void onResponse(String response) {
				System.out.println("response:"+response);
				ParseDataHandler parseDataHandler = new ParseDataHandler(mHandler,response);
				parseDataHandler.setParseDataCallBack(new ParseDataCallBack() {

					@Override
					public BaseResponseData executeParseData(String data) {
						BaseResponseData result = JsonUtil.toObject(data, BaseResponseData.class);
						return result;
					}

					@Override
					public void onResult(BaseResponseData t) {
						dimissMaterialLoadDialog();
						if(HttpHelper.HttpStatus.SUCCESS_CODE.equals(t.getCode())){
							showToast(R.string.label_upload_success);
//							ComeBackHomeReceiver.sendComeBackHome(mContext);
							Glide.with(mContext).load(HttpHelper.OSS_IMAGE_HOST+faceImg)
				            .centerCrop()
				            .placeholder(R.drawable.ic_me)
				            .error(R.drawable.ic_me)
				            .into(vRoundImg);
							System.out.println();
							mUserInfo.setFaceImg(HttpHelper.OSS_IMAGE_HOST+faceImg);
							mainApplication.getFinalDB().update(mUserInfo);
						}else{
							if(HttpHelper.HttpStatus.LOGIN_CONFICT_EXIT.equals(t.getCode())){
								mainApplication.clearDB();
								ShoppingCartNumChangeReceiver.sendCartNumChanged(mContext, 0);
								String msg = t.getMsg();
								if(!TextUtils.isEmpty(msg) && msg.trim().length() > 0){
									showToast(msg);
								}
								Intent intent = new Intent(mContext,HomeActivity.class);
								intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
								intent.putExtra("module", "Login");
								startActivity(intent);
							}
						}
					}
				});
				parseDataHandler.start();
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				dimissMaterialLoadDialog();
				showNetErrorInfo();
			}
		});
		request.setHttpHeader(Utils.getHttpHeader(mContext,mUserInfo.getToken()));
		request.setParams(params);
		request.setTag(TAG);
		queue.add(request);
	}




manifest:



    

    
    
    
    

    
        
            
                

                
            
        
    


layout:


    

源码地址:
http://download.csdn.net/detail/legend12300/9488326




你可能感兴趣的:(阿里云,api,存储,上传图片,OSS)