简介
对象存储服务(Object Storage Service,OSS)是一种海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。
存储类型(Storage Class):OSS 提供标准、低频访问、归档三种存储类型,全面覆盖从热到冷的各种数据存储场景。其中标准存储类型提供高可靠、高可用、高性能的对象存储服务,能够支持频繁的数据访问;低频访问存储类型适合长期保存不经常访问的数据(平均每月访问频率 1 到 2 次),存储单价低于标准类型;归档存储类型适合需要长期保存(建议半年以上)的归档数据,在三种存储类型中单价最低。
OSS可用于图片、音视频、日志等海量文件的存储。各种终端设备、Web网站程序、移动应用可以直接向OSS写入或读取数据。
OSS支持流式写入和文件写入两种方式。
对象oss提供功能:上传及下载、图片处理、域名绑定与使用、Bucket Policy等
简单上传指的是使用OSS API中的PutObject方法上传单个文件(Object)。
简单上传分为流式上传和文件上传。流式上传使用InputStream作为文件的数据源。文件上传使用本地文件作为OSS文件的数据源。
如果Object是公共读/公共读写权限,那么访问URL的格式为:Bucket名称.Endpoint/Object名称
外网访问URL:aliyun-abc.oss-cn-hangzhou.aliyuncs.com/123.jpg
阿里云内网ECS/VPC访问URL:aliyun-abc.oss-cn-hangzhou-internal.aliyuncs.com/123.jpg
例如:https://test.oss-cn-hangzhou.aliyuncs.com/1.jpg
入门demo
pom.xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
application.yml
#OSS
aliyun.oss.endpoint=https://oss-cn-beijing.aliyuncs.com/
aliyun.oss.access-id=xxxxxx //此处填你在阿里云控制台的AccessKey ID
aliyun.oss.access-key=xxxxxx //此处填你在阿里云控制台的Access Key Secret
aliyun.oss.bucket=xxxxxx //此处填你自己创建oss的bucketName
aliyun.oss.dir=xxxxxx //自定义的bucketName下的目录
OSSClientUtil.java
package com.ph.bscCloud.common.utils;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;
@Slf4j
@Configuration
public class OSSClientUtil {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.access-id}")
private String accessKeyId;
@Value("${aliyun.oss.access-key}")
private String accessKeySecret;
@Value("${aliyun.oss.dir}")
private String filedir;
@Value("${aliyun.oss.bucket}")
private String bucketName;
private OSSClient ossClient;
/**
* 初始化
*/
public void init() {
ClientConfiguration conf = new ClientConfiguration();
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
/* 通过一个Bucket对象来创建 */
CreateBucketRequest bucketObj = new CreateBucketRequest(null);// 构造函数入参为Bucket名称,可以为空
bucketObj.setBucketName(bucketName);// 设置bucketObj名称
bucketObj.setCannedACL(CannedAccessControlList.PublicReadWrite);// 设置bucketObj访问权限acl
ossClient.createBucket(bucketObj);// 创建Bucket
}
/**
* 销毁
*/
public void destory() {
if (ossClient != null) {
ossClient.shutdown();
}
}
/**
* 上传图片
*
* @param url
* @throws Exception
*/
public String uploadImg2Oss(String url) throws Exception {
File fileOnServer = new File(url);
FileInputStream fin;
try {
fin = new FileInputStream(fileOnServer);
String[] split = url.split("/");
this.uploadFile2OSS(fin, split[split.length - 1]);
return split[split.length - 1];
} catch (FileNotFoundException e) {
throw new Exception("图片上传失败");
}
}
public String uploadImg2Oss(MultipartFile file) throws Exception {
if (file.getSize() > 1024 * 1024 * 2) {
throw new Exception("上传图片大小不能超过2M!");
}
String originalFilename = file.getOriginalFilename();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
try {
InputStream inputStream = file.getInputStream();
this.uploadFile2OSS(inputStream, name);
return name;
} catch (Exception e) {
throw new Exception("图片上传失败");
}
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
if (StringUtils.isNotEmpty(StringUtils.trim(fileUrl))) {
String[] split = fileUrl.split("/");
return this.getUrl(this.filedir + split[split.length - 1]);
}
return null;
}
/**
* 上传到OSS服务器 如果同名文件会覆盖服务器上的
*
* @param instream 文件流
* @param fileName 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2OSS(InputStream instream, String fileName) {
String ret = "";
try {
//创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
//上传文件
PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
*
* @param FilenameExtension 文件后缀
* @return String
*/
public static String getcontentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase("bmp")) {
return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase("gif")) {
return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase("jpeg") ||
FilenameExtension.equalsIgnoreCase("jpg") ||
FilenameExtension.equalsIgnoreCase("png")) {
return "image/jpeg";
}
if (FilenameExtension.equalsIgnoreCase("html")) {
return "text/html";
}
if (FilenameExtension.equalsIgnoreCase("txt")) {
return "text/plain";
}
if (FilenameExtension.equalsIgnoreCase("vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equalsIgnoreCase("pptx") ||
FilenameExtension.equalsIgnoreCase("ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equalsIgnoreCase("docx") ||
FilenameExtension.equalsIgnoreCase("doc")) {
return "application/msword";
}
if (FilenameExtension.equalsIgnoreCase("xml")) {
return "text/xml";
}
return "image/jpeg";
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
String imgName = url.toString();
int index = imgName.indexOf("?");
imgName = imgName.substring(0, index);
return imgName;
}
return null;
}
public void delete(String key) {
ossClient.deleteObject(bucketName, key);
}
}
代码中调用
String fileName = file.getOriginalFilename().toLowerCase();
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
String fileAlias = IDUtil.getID();;
String url = null;
InputStream inputStream = file.getInputStream();
OSSClientUtil oss = new OSSClientUtil();
oss.init();
oss.uploadFile2OSS(inputStream, fileAlias + "." + suffixName);
url = oss.getImgUrl(fileAlias + "." + suffixName);
oss.destory();
没了…