一、springboot集成oss
1、首先贴上配置信息:
oss:
accessId: xxxxxxxxx #根据自己申请的填写
accessKey: xxxxxxxxxxxxxx #根据自己申请的填写
publicBucket: ab-pub #公共读写,一般配置上传的客户端版本信息
privateBucket: ab-private #私有读写,一般配置上传的图片信息等
endpoint: oss-cn-beijing.aliyuncs.com #外网配置,这里配置的是北京区域的,根据自己申请的填写
internalEndpoint: oss-cn-beijing-internal.aliyuncs.com #内网配置,这里配置的是北京区域的,根据自己申请的填写
iosObject: apk/ios/ #IOS版本包目录,根据实际业务自己配置
androidObject: apk/android/#安卓版本包目录,根据实际业务自己配置
heagerObject: head_portrait/ #用户图像
photoObject: task_photo/ #用户上传的业务图片
expire: 86400000 #24 * 3600 * 1000 #连接有效期
2、配置OSS属性类
package com.ftd.pcms.common.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "oss")
@Data
public class OssProperties {
private String accessId;
private String accessKey;
private String publicBucket;
private String privateBucket;
private String endpoint;
private String internalEndpoint;
private String iosObject;
private String androidObject;
private String heagerObject;
private String photoObject;
private Integer expire;
private String roleSessionName;
public OssProperties() {
}
}
这里因为我用了lombok插件,所以使用了@data注解,这个注解的意思是生成set、get等方法,不会用的可以百度下,这里就不想洗说了,如果不想用,可以去掉data注解,然后手动生成set、get方法就行。
3、OSS对象存储工具类
package com.ftd.pcms.common.utils;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.ftd.pcms.common.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
/**
* @author lijz
* @description TODO OSS文件服务器操作类
* @date 2019/3/22 15:36
**/
@Slf4j
@Component
public class OssManage {
@Autowired
private OssProperties ossProperties;
public OSSClient init() {
// 初始化一个外网OSSClient
OSSClient client = new OSSClient(ossProperties.getEndpoint(), ossProperties.getAccessId(), ossProperties.getAccessKey());
return client;
}
public OSSClient initInternal() {
// 初始化一个内网OSSClient
OSSClient client = new OSSClient(ossProperties.getInternalEndpoint(), ossProperties.getAccessId(), ossProperties.getAccessKey());
return client;
}
/**
* @author lijz
* @description TODO 上传客户端版本包
* @date 2019/3/22 15:54
* @param content
* @param key
* @param mimeType
* @param apkType
* @return java.lang.String
**/
public String uploadApk(InputStream content, String key, String mimeType,Byte apkType) throws Exception {
String object ="";
if(1==apkType){
object = ossProperties.getIosObject();
}else{
object = ossProperties.getAndroidObject();
}
// 进行初始化 TODO 改成局部变量 或 改成单例模式
OSSClient client = init();
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentType(mimeType);
// 上传Object.
log.info("*****************uploadApk上传包到oss服务器开始"+ key);
key = object + key;
PutObjectResult result = client.putObject(ossProperties.getPublicBucket(), key, content, meta);
client.shutdown();//上传完成后关闭
// meta.wait(50000);
log.info("*****************uploadApk上传包到oss服务器结束"+ key);
// return result.getETag();
return key;
}
/**
* @author lijz
* @description TODO 上传图片
* @date 2019/3/22 15:58
* @param content
* @param key
* @param mimeType
* @param imagType 1代表用户头像 2代表任务照片
* @return java.lang.String
**/
public String uploadImage(InputStream content, String key, String mimeType,Integer imagType) throws Exception {
String object ="";
if(1==imagType){
object = ossProperties.getHeagerObject();
}else{
object = ossProperties.getPhotoObject();
}
// 进行初始化 TODO 改成局部变量 或 改成单例模式
OSSClient client = init();
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentType(mimeType);
// 上传Object.
log.info("*****************uploadImage上传图片到oss服务器开始"+ key);
key = object+key;
PutObjectResult result = client.putObject(ossProperties.getPrivateBucket(), key, content, meta);
client.shutdown();//上传完成后关闭
// meta.wait(50000);
log.info("*****************uploadImage上传图片到oss服务器结束"+ key);
// return result.getETag();
return key;
}
/**
* @author lijz
* @description TODO 根据样式获取oss服务器上图片路径
* @date 2019/3/22 16:19
* @param key
* @param type 1、图片2、APK包
* @return java.lang.String
**/
public String getURl(String key,Integer type) {
return getURlByStyle(key, type,null);
}
/**
* @author lijz
* @description TODO 根据样式获取oss服务器上图片路径
* @date 2019/3/22 16:19
* @param key
* @param type 1、图片2、APK包
* @param style
* @return java.lang.String
**/
public String getURlByStyle(String key,Integer type, String style) {
OSSClient client = init();
String bucket = "";
if(1==type){
bucket = ossProperties.getPrivateBucket();
}else{
bucket = ossProperties.getPublicBucket();
}
log.info("*****************getImgURlByStyle开始*****************" + key);
if(StringUtils.isEmpty(key)){
return "";
}
Date expires = new Date(new Date().getTime() + ossProperties.getExpire()); // 30
GeneratePresignedUrlRequest generatePresignedUrlRequest;
generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket, key);
generatePresignedUrlRequest.setExpiration(expires);
if(StringUtils.isNotBlank(style)){
generatePresignedUrlRequest.addQueryParameter("x-oss-process", style);
}
URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
log.info("*****************getImgURlByStyle结束*****************" + key + "************" + url.toString());
return url.toString();
}
/**
* @author lijz
* @description TODO 根据key获取oss服务器上的文件流
* @date 2019/3/22 16:25
* @param key
* @param type 1、图片2、APK包
* @return java.io.InputStream
**/
public InputStream getObject(String key,Integer type) {
OSSClient client = init();
String bucket = "";
if(1==type){
bucket = ossProperties.getPrivateBucket();
}else{
bucket = ossProperties.getPublicBucket();
}
OSSObject object = null;
object = client.getObject(bucket, key);
object.getObjectMetadata().getContentType();
// 获取Object的输入流
InputStream objectContent = object.getObjectContent();
return objectContent;
}
/**
* @Description: 删除文件
* @param key OSS文件服务器上文件的唯一标识
* @param type 1、图片2、APK包
* @ReturnType:void
* @exception
* @Since: 2019/3/22 16:25
* @Author: lijz
*/
public void deleteFile(String key,Integer type) {
OSSClient client = init();
String bucket = "";
if(1==type){
bucket = ossProperties.getPrivateBucket();
}else{
bucket = ossProperties.getPublicBucket();
}
client.deleteObject(bucket, key);
}
/**
* @Description: 断点上传文件到OSS文件服务器
* @param content
* 文件流
* @param key
* 上传为OSS文件服务器的唯一标识
* @param position
* 位置
* @throws Exception
* @ReturnType:String appendObjectResult.getNextPosition().toString()。
* @exception
* @Since: 2019/3/22 16:25
* @Author: lijz
*/
public String appendObjectFile(InputStream content, String key, int position, String mimeType) throws Exception {
// 进行初始化
OSSClient client = init();
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentLength(position);
meta.setContentType(mimeType);
meta.setCacheControl("no-cache");
meta.setContentEncoding("utf-8");
// 上传
log.info("*****************断点上传图片到oss服务器开始*****************" + key);
AppendObjectRequest appendObjectRequest = new AppendObjectRequest(ossProperties.getPrivateBucket(), key, content, meta);
appendObjectRequest.setPosition(Long.valueOf(position));
AppendObjectResult appendObjectResult = client.appendObject(appendObjectRequest);
log.info("*****************断点上传图片到oss服务器结束*****************" + key);
return appendObjectResult.getNextPosition().toString();
}
}
本人之前也没用用过oss,是之前换到新的公司才接触的,当时公司的项目是springmvc的,只是在之前项目的启发下,自己集成的springboot项目,如果有不合理的地方或者有更好的集成方案,欢迎给提出,下面贴上springmvc的整合方式。
二、springmvc整合OSS
1、同样的先贴上配置信息
在这之前先贴上项目目录
然后在这个配置文件中配置相关信息:
## OSS sitting start
OSS_ACCESS_KEY_ID=xxxxxxxxxx
OSS_ACCESS_KEY_SECRET=xxxxxxxxxxxxxxxxxxx
OSS_ENDPOINT=https://oss-cn-beijing.aliyuncs.com
OSS_ENDPOINT_INTERNAL=https://oss-cn-beijing.aliyuncs.com
OSS_BUCKETNAME=xxxxxx
OSS_SUB_BUCKETNAME=xxxxxxxx
OSS_SUB_SUB_BUCKETNAME=xxxxxxx
OSS_OUT_OF_DATE=1800000
配置跟上面跟springboot的配置差不多,注释就不写了
2、oss对象操作工具类
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.liveneo.msplatform.common.utils.LogUtil;
import com.liveneo.msplatform.common.utils.SysConstant;
import com.liveneo.msplatform.modules.survey.oss.OssConfig;
import com.liveneo.msplatform.modules.survey.oss.OssHopler;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
/**
* @Title: OSS文件服务器操作类
* @Description:
* @Author:YJX
* @Since:2015-8-22 下午12:58:58
* @Version:1.0.0
*/
public class OssManage {
public static String ACCESS_KEY_ID = null;
public static String ACCESS_KEY_SECRET = null;
public static String ENDPOINT = null; //公网地址
public static String ENDPOINT_INTERNAL = null; //内网地址
public static String BUCKETNAME = null;
public static String SUB_BUCKETNAME = null;
public static String ZX_BUCKETNAME = null;
public static String OUT_OF_DATE = null;
private OSSClient client = null;
private OSSClient clientInternal = null;
private ObjectMetadata meta = null;
private static String SYNC_PREFIX = null; //同步app前缀
private static String SYNC_SUFFFIX = null; //同步app后缀
private static String SYNC_SUB_SUFFFIX = null; //同步app后缀子节点
static {
try {
ACCESS_KEY_ID = SysConstant.get("OSS_ACCESS_KEY_ID");
ACCESS_KEY_SECRET = SysConstant.get("OSS_ACCESS_KEY_SECRET");
ENDPOINT = SysConstant.get("OSS_ENDPOINT");
ENDPOINT_INTERNAL = SysConstant.get("OSS_ENDPOINT_INTERNAL");
BUCKETNAME = SysConstant.get("OSS_BUCKETNAME");
SUB_BUCKETNAME = SysConstant.get("OSS_SUB_BUCKETNAME");
ZX_BUCKETNAME = SysConstant.get("OSS_ZX_BUCKETNAME");
OUT_OF_DATE = SysConstant.get("OSS_OUT_OF_DATE");
SYNC_PREFIX = SysConstant.get("SYNC_PREFIX");
SYNC_SUFFFIX = SysConstant.get("SYNC_SUFFFIX");
SYNC_SUB_SUFFFIX = SysConstant.get("SYNC_SUB_SUFFFIX");
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
public void init() {
// 初始化一个OSSClient
if(client==null){
client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
if(meta==null){
meta = new ObjectMetadata();
}
}
public void initInternal() {
// 初始化一个OSSClient
if(clientInternal==null){
clientInternal = new OSSClient(ENDPOINT_INTERNAL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
if(meta==null){
meta = new ObjectMetadata();
}
}
/**
* @Description: 上传文件到OSS文件服务器
* @param content
* 文件流
* @param key
* 上传为OSS文件服务器的唯一标识
* @param mimeType
* 文档类型
* @throws Exception
* @ReturnType:String OSSObject的ETag值。
* @exception
* @Since:2015-8-22 下午02:00:19
* @Author:YJX
*/
public String uploadFile(InputStream content, String key, String mimeType,String loguuid) throws Exception {
// 进行初始化 TODO 改成局部变量 或 改成单例模式
init();
// initInternal();
// 必须设置ContentLength
meta.setContentType(mimeType);
// 上传Object.
LogUtil.printOSSLog("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+"*****************" + key);
LogUtil.printOSSLog("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+">client state:"+client);
PutObjectResult result = client.putObject(BUCKETNAME, SUB_BUCKETNAME+"/"+key, content, meta);
client.shutdown();//上传完成后关闭
// meta.wait(50000);
LogUtil.printOSSLog("*****************uploadFile上传图片到oss服务器结束>loguuid="+loguuid+"*****************" + key);
return result.getETag();
}
/**
* @Description: 上传文件到OSS文件服务器
* @param content
* 文件流
* @param key
* 上传为OSS文件服务器的唯一标识
* @param mimeType
* 文档类型
* @throws Exception
* @ReturnType:String OSSObject的ETag值。
* @exception
* @Since:2015-8-22 下午02:00:19
* @Author:YJX
*/
public String uploadFileForAppVersion(InputStream content, String key, String mimeType,String loguuid) throws Exception {
// 进行初始化 TODO 改成局部变量 或 改成单例模式
//inner net
clientInternal = new OSSClient(ENDPOINT_INTERNAL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentType(mimeType);
// 上传Object.
LogUtil.printOSSLog("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+"*****************" + key);
LogUtil.printOSSLog("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+">client state:"+client);
PutObjectResult result = clientInternal.putObject(BUCKETNAME, key, content, meta);
clientInternal.shutdown();//上传完成后关闭
//out net
LogUtil.printOSSLog("*****************uploadFile上传图片到oss服务器结束>loguuid="+loguuid+"*****************" + key);
return result.getETag();
}
/**
*
* @Description:获取OSS服务器上资源文件路径
* @Since:2016年12月28日 上午11:46:56
* @Author:hjt
*/
public String getImgURl(String key) {
return getImgURlByStyle(key, null);
}
/**
*
* @Description:根据样式获取oss服务器上资源文件路径
* @Since:2016年12月28日 上午11:44:50
* @Author:hjt
*/
public String getImgURlByStyle(String key, String style) {
init();
LogUtil.printOSSLog("*****************getImgURlByStyle开始*****************" + key);
if(StringUtils.isEmpty(key)){
return "";
}
Date expires = new Date(new Date().getTime() + Integer.parseInt(OUT_OF_DATE)); // 30
GeneratePresignedUrlRequest generatePresignedUrlRequest;
if (key.startsWith("MP")) {
generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, SUB_BUCKETNAME+"/"+key);
} else {
if(key.indexOf(OssConfig.Z_OBJECT_VIDEO) > -1){
return OssHopler.getVideoPath(key);
} else {
return OssHopler.getPath(key, style);
}
// generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ZX_BUCKETNAME, key);
}
generatePresignedUrlRequest.setExpiration(expires);
if(StringUtils.isNotBlank(style)){
generatePresignedUrlRequest.addQueryParameter("x-oss-process", style);
}
URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
LogUtil.printOSSLog("*****************getImgURlByStyle结束*****************" + key + "************" + url.toString());
return url.toString();
}
/**
* @Description:根据key获取oss服务器上的ipa文件公网地址
* @param key
* @return
* @ReturnType:String
* @exception
* @Since:2015-11-3 下午02:35:42
* @Author:yleilei
*/
public String getIpaURl(String key) {
LogUtil.printOSSLog("*****************getIpaURl开始*****************" + key);
// client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
init();
Date expires = new Date(new Date().getTime() + 10 * 365 * 24 * 3600 * 1000);
GeneratePresignedUrlRequest generatePresignedUrlRequest;
if (key.startsWith("MP")) {
generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, SUB_BUCKETNAME+"/"+key);
} else {
generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ZX_BUCKETNAME, key);
}
generatePresignedUrlRequest.setExpiration(expires);
URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
LogUtil.printOSSLog("*****************getIpaURl结束*****************" + key + "*************" + url.toString());
return url.toString();
}
/**
* @Description: 根据key获取oss服务器上的图片地址
* @param key
* @return
* @ReturnType:String
* @exception
* @Since:2015-8-26 下午04:57:46
* @Author:YJX
*/
public InputStream getObject(String key) {
init();
OSSObject object = null;
if (key.startsWith("MP")) {
object = client.getObject(BUCKETNAME, SUB_BUCKETNAME+"/"+key);
} else {
return OssHopler.getObject(key);
// object = client.getObject(ZX_BUCKETNAME, key);
}
object.getObjectMetadata().getContentType();
// 获取Object的输入流
InputStream objectContent = object.getObjectContent();
return objectContent;
}
/**
* @Description:删除文件
* @param key
* OSS文件服务器上文件的唯一标识
* @ReturnType:void
* @exception
* @Since:2015-8-22 下午02:21:23
* @Author:YJX
*/
public void deleteFile(String key) {
init();
client.deleteObject(BUCKETNAME, key);
}
/**
* @Description: 断点上传文件到OSS文件服务器
* @param content
* 文件流
* @param key
* 上传为OSS文件服务器的唯一标识
* @param position
* 位置
* @throws Exception
* @ReturnType:String appendObjectResult.getNextPosition().toString()。
* @exception
* @Since:2015-10-10 下午04:00:19
* @Author:zhoupan
*/
public String appendObjectFile(InputStream content, String key, int position, String mimeType) throws Exception {
// 进行初始化
init();
// 必须设置ContentLength
meta.setContentLength(position);
meta.setContentType(mimeType);
meta.setCacheControl("no-cache");
meta.setContentEncoding("utf-8");
// 上传
LogUtil.printOSSLog("*****************断点上传图片到oss服务器开始*****************" + key);
AppendObjectRequest appendObjectRequest = new AppendObjectRequest(BUCKETNAME, key, content, meta);
appendObjectRequest.setPosition(Long.valueOf(position));
AppendObjectResult appendObjectResult = client.appendObject(appendObjectRequest);
LogUtil.printOSSLog("*****************断点上传图片到oss服务器结束*****************" + key);
return appendObjectResult.getNextPosition().toString();
}
public String getImgInnerURl(String key) {
init();
// LogUtils.info("*****************getImgURl开始*****************" + key);
if(StringUtils.isEmpty(key)){
return "";
}
Date expires = new Date(new Date().getTime() + Integer.parseInt(OUT_OF_DATE)); // 30
GeneratePresignedUrlRequest generatePresignedUrlRequest;
if (key.startsWith("MP")) {
generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, SUB_BUCKETNAME+"/"+key);
} else {
generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ZX_BUCKETNAME, key);
}
generatePresignedUrlRequest.setExpiration(expires);
URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
// LogUtils.info("*****************getImgURl结束*****************" + key + "************" + url.toString());
return url.toString();
}
/**
* 删除key并且上传
* @uthor: hjt
* @date: 2018年2月6日 下午5:12:57
*/
public String uploadFileForApp(InputStream content, String key) throws Exception {
clientInternal = new OSSClient(ENDPOINT_INTERNAL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
ObjectMetadata meta = new ObjectMetadata();
String sync_key = SYNC_SUFFFIX + "/" + SYNC_SUB_SUFFFIX + "/" + key;
clientInternal.deleteObject(SYNC_PREFIX, sync_key);
PutObjectResult result = clientInternal.putObject(SYNC_PREFIX, sync_key,
content, meta);
clientInternal.shutdown();//上传完成后关闭
return result.getETag();
}
}
工具类里面通过SysConstant.get()方法将各个属性获取到了,SysConstant这个类是读取配置文件的类,我在下面贴一下:
3、读取配置文件操作类
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* 常量类
* @author hjt
*
*/
public class SysConstant {
/* 私有构造方法,防止被实例化 */
private SysConstant(){}
/**
* 配置文件实例
*/
private static final String PROP_FILE_NAME = "/sysconst.properties";
public static Properties propertie = null;
static {
propertie = new Properties();
InputStream inputStream = SysConstant.class.getResourceAsStream(PROP_FILE_NAME);
//解决中文乱码
BufferedReader buff = new BufferedReader(new InputStreamReader(inputStream));
try {
propertie.load(buff);
inputStream.close();
} catch (IOException e) {
}
}
/**
*
* @Description 获取常量值
* @param key
* @return
*/
public static String get(String key){
return (String) SysConstant.propertie.get(key);
}
/**
*
* @Description 提供标签:获取常量值
* @param key
* @return
*/
public static String getCnstPro(String key){
return get(key);
}
/**
* @author li_jiazhi
* @create 2018年10月8日下午4:05:55
* @param path
* @return
* 读取资源目录下文件的内容返回字符串(如腾讯配置的公钥私钥)
*/
public static String getKeys(String path) {
String key = null;
try {
//读取私钥的内容
//PS:不要把私钥文件暴露到外网直接下载了哦
InputStream in = SysConstant.class.getResourceAsStream(path);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
byte[] data = out.toByteArray();
in.close();
key = new String(data);
// System.out.println(key);
} catch (Exception e ) {
e.printStackTrace();
}
return key;
}
}
之前也说了,springboot的集成是我参考springmvc的配置集成的,springmvc的集成是公司以前的同事集成的,如果springmvc的方式对各位有帮助,要谢就谢我之前的同事吧,我只是代码的搬运工,哈哈。。。。