说起阿里云OSS,那作用和功能都是非常强大的,它可以存放图片,音频,视频等资源文件,这些资源文件,你不必存放到服务器的硬盘里,这样既可以节省服务器硬盘空间,又可以降低服务器的读写压力,非常适合大并发的架构。
这里就让小编带你入门吧!
一,准备工作
无论怎么样,你需要准备一个阿里云账号,点击:注册阿里云
输入相关信息,然后注册成功以后,点击
编辑
然后注册成功了,实名一下阿里云账号。打开实名入口,选择个人实名或者企业实名。
编辑
如果你是个人用户,则建议你使用个人实名,如果你是企业用户,则建议你使用企业实名,这里要注意一下,个人实名的阿里云账号,在消费后,是无法索取企业发票的。
二,选择OSS的配置
如果你打算存100G的视频或者音频,那么你接下来点击:OSS选择配置入口
编辑
选择:OSS资源包,资源包类型:标准-本地冗余存储,地域:中国内地通用,本地冗余存储规格选择:100GB。然后,直接点击:立即购买即可。
三,管理桶
3.1,创建桶
打开OSS桶管理
编辑
点击:创建Bucket
选择:存储类型,存储冗余类型,读写权限
就可以创建一个桶了。
3.2,删除桶中的文件
选中,想要删除的文件,点击删除。即可
编辑
3.3,上传文件
选择要上传的文件,点击文件上传
编辑
四,配置域名
一般来说,我们的项目需要单独解析个子域名到,阿里云的OSS,在OSS的桶详情里,有个Bucket 配置,点击:域名管理,
编辑
点击:绑定域名
编辑
输入:域名,并点击:自动添加 CNAME 记录
这样就可以添加个单独的域名。
五,配置CDN
打开OOS桶-》Bucket 配置-》域名管理
点击:阿里云CDN加速配置
编辑
添加了域名之后,
编辑
在去域名那边,添加解析。然后点击:点击验证
然后系统会自动设置源站信息,
然后点击:一键配置
编辑
在然后按照指示添加一个:CNAME解析
这样阿里云OSS添加了CDN加速。
编辑
接下来开启,CDN缓存自动刷新,和OSS接口动作同步,比如通过接口上传了个文件到OSS里。
编辑
CDN缓存自动刷新配置完成
编辑
如果域名是走HTTPS的,则在证书托管板块,上传SSL证书的公钥和私钥。
六,使用代码对接OSS
准备访问密钥AcessKey:AK,用户通过用户标识AccessKeyId和密钥AccessKeySecret对称加密的方式进行身份验证,可以由Bucket创建者和Bucket授权者创建
在阿里云的后台创建获取
编辑
接下来我以Java为例,来讲解
6.1,Java简单上传
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import java.io.ByteArrayInputStream; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 String bucketName = "examplebucket"; // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 String objectName = "exampledir/exampleobject.txt"; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // 填写字符串。 String content = "Hello OSS,你好世界"; // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes())); // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 上传字符串。 PutObjectResult result = ossClient.putObject(putObjectRequest); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
6.2,Java表单上传
import com.aliyun.oss.common.utils.BinaryUtil; import com.aliyun.oss.internal.OSSUtils; import com.aliyun.oss.model.Callback; import org.apache.commons.codec.binary.Base64; import javax.activation.MimetypesFileTypeMap; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import com.aliyun.oss.ClientException; public class PostObjectSample { // 填写待上传的本地文件的完整路径。 private String localFilePath = "yourLocalFile"; // Endpoint以杭州为例,其它Region请按实际情况填写。 private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID"); String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET"); // 填写Bucket名称。 private String bucketName = "yourBucketName"; // 填写不包含Bucket名称在内的Object的完整路径。 private String objectName = "yourObjectName"; // 设置回调服务器地址,例如http://oss-demo.oss-cn-hangzhou.aliyuncs.com:23450或http://127.0.0.1:9090。 private String callbackServerUrl = "yourCallbackServerUrl"; // 设置回调请求消息头中Host的值,例如oss-cn-hangzhou.aliyuncs.com。 private String callbackServerHost = "yourCallbackServerHost"; /** * 表单上传。 * @throws Exception */ private void PostObject() throws Exception { // 在URL中添加Bucket名称,添加后URL格式为http://yourBucketName.oss-cn-hangzhou.aliyuncs.com。 String urlStr = endpoint.replace("http://", "http://" + bucketName+ "."); // 设置表单Map。 Map<String, String> formFields = new LinkedHashMap<String, String>(); // 设置文件名称。 formFields.put("key", this.objectName); // 设置Content-Disposition。 formFields.put("Content-Disposition", "attachment;filename=" + localFilePath); // 设置回调参数。 // Callback callback = new Callback(); // 设置回调服务器地址,例如http://oss-demo.oss-cn-hangzhou.aliyuncs.com:23450或http://127.0.0.1:9090。 // callback.setCallbackUrl(callbackServerUrl); // 设置回调请求消息头中Host的值,如oss-cn-hangzhou.aliyuncs.com。 // callback.setCallbackHost(callbackServerHost); // 设置发起回调时请求Body的值。 // callback.setCallbackBody("{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}}"); // 设置发起回调请求的Content-Type。 // callback.setCalbackBodyType(Callback.CalbackBodyType.JSON); // 设置发起回调请求的自定义参数,由Key和Value组成,Key必须以x:开始,且必须小写。 // callback.addCallbackVar("x:var1", "value1"); // callback.addCallbackVar("x:var2", "value2"); // 在表单Map中设置回调参数。 // setCallBack(formFields, callback); // 设置OSSAccessKeyId。 formFields.put("OSSAccessKeyId", accessKeyId); String policy = "{\"expiration\": \"2120-01-01T12:00:00.000Z\",\"conditions\": [[\"content-length-range\", 0, 104857600]]}"; String encodePolicy = new String(Base64.encodeBase64(policy.getBytes())); // 设置policy。 formFields.put("policy", encodePolicy); // 生成签名。 String signaturecom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(accessKeySecret, encodePolicy); // 设置签名。 formFields.put("Signature", signaturecom); String ret = formUpload(urlStr, formFields, localFilePath); System.out.println("Post Object [" + this.objectName + "] to bucket [" + bucketName + "]"); System.out.println("post reponse:" + ret); } private static String formUpload(String urlStr, Map<String, String> formFields, String localFile) throws Exception { String res = ""; HttpURLConnection conn = null; String boundary = "9431149156168"; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(30000); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream out = new DataOutputStream(conn.getOutputStream()); // 遍历读取表单Map中的数据,将数据写入到输出流中。 if (formFields != null) { StringBuffer strBuf = new StringBuffer(); Iterator<Map.Entry<String, String>> iter = formFields.entrySet().iterator(); int i = 0; while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); String inputName = entry.getKey(); String inputValue = entry.getValue(); if (inputValue == null) { continue; } if (i == 0) { strBuf.append("--").append(boundary).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); strBuf.append(inputValue); } else { strBuf.append("\r\n").append("--").append(boundary).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); strBuf.append(inputValue); } i++; } out.write(strBuf.toString().getBytes()); } // 读取文件信息,将要上传的文件写入到输出流中。 File file = new File(localFile); String filename = file.getName(); String contentType = new MimetypesFileTypeMap().getContentType(file); if (contentType == null || contentType.equals("")) { contentType = "application/octet-stream"; } StringBuffer strBuf = new StringBuffer(); strBuf.append("\r\n").append("--").append(boundary) .append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"file\"; " + "filename=\"" + filename + "\"\r\n"); strBuf.append("Content-Type: " + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 读取返回数据。 strBuf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { strBuf.append(line).append("\n"); } res = strBuf.toString(); reader.close(); reader = null; } catch (ClientException e) { System.err.println("Send post request exception: " + e); System.err.println(e.getErrorCode()+" msg="+e.getMessage()); throw e; } finally { if (conn != null) { conn.disconnect(); conn = null; } } return res; } private static void setCallBack(Map<String, String> formFields, Callback callback) { if (callback != null) { String jsonCb = OSSUtils.jsonizeCallback(callback); String base64Cb = BinaryUtil.toBase64String(jsonCb.getBytes()); formFields.put("callback", base64Cb); if (callback.hasCallbackVar()) { Map<String, String> varMap = callback.getCallbackVar(); for (Map.Entry<String, String> entry : varMap.entrySet()) { formFields.put(entry.getKey(), entry.getValue()); } } } } public static void main(String[] args) throws Exception { PostObjectSample ossPostObject = new PostObjectSample(); ossPostObject.PostObject(); } }
6.3,Java下载到本地文件
package com.aliyun.oss.demo; import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.GetObjectRequest; import java.io.File; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; //从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 String bucketName = "examplebucket"; // 填写不包含Bucket名称在内的Object完整路径,例如testfolder/exampleobject.txt。 String objectName = "testfolder/exampleobject.txt"; // 填写Object下载到本地的完整路径。 String pathName = "D:\\localpath\\examplefile.txt"; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。 // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。 ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName)); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
6.4,Java删除文件
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 String bucketName = "examplebucket"; // 填写文件完整路径。文件完整路径中不能包含Bucket名称。 String objectName = "exampleobject.txt"; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // 删除文件或目录。如果要删除目录,目录必须为空。 ossClient.deleteObject(bucketName, objectName); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
6.5,批量删除文件
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.DeleteObjectsRequest; import com.aliyun.oss.model.DeleteObjectsResult; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 String bucketName = "examplebucket"; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); try { // 删除文件。 // 填写需要删除的多个文件完整路径。文件完整路径中不能包含Bucket名称。 List<String> keys = new ArrayList<String>(); keys.add("exampleobjecta.txt"); keys.add("testfolder/sampleobject.txt"); keys.add("exampleobjectb.txt"); DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withEncodingType("url")); List<String> deletedObjects = deleteObjectsResult.getDeletedObjects(); try { for(String obj : deletedObjects) { String deleteObj = URLDecoder.decode(obj, "UTF-8"); System.out.println(deleteObj); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }