文档:https://help.aliyun.com/document_detail/44075.html
一,添加依赖
<!-- oss begin -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.13.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.4</version>
</dependency>
<!-- oss end -->
二,配置文件
#aliyun oss
aliyun:
oss_bucket_map: # Map-> sence : bucket
advertisement: bucketName
test: testval
main_domain: bucketName
aliyun_sms_sign: 1
aliyun_sms_templet: 1
ossEndpointValue: oss-cn-hangzhou.aliyuncs.com
ossEndpointInner: inner
ossAccessKeyId: 你的AccessKeyId
ossAccessKeySecret: 你的AccessKeySecret
ossStsRegion: region
ossStsSessionName: session_name
ossStsExpire: 1000
ossStsRoleId: 1
ossStsEndpoint: endpoint
ossStsAccessKeyId: accessKeyId
ossStsAccessKeySecret: accessKeySecret
三,实体层
AliyunOssAutoSignRequest
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @description :
* @auther Tyler
* @date 2021/8/16
*/
/**
* 获得阿里云oss的文件类型
*/
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
public class AliyunOssAutoSignRequest {
/**
* 文件场景
*/
@JsonProperty("file_scene")
private String fileScene;
/**
* 文件名称
*/
@JsonProperty("file_name")
private String fileName;
}
aliyun的OSS配置实例
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
/**
* @description :
* @auther Tyler
* @date 2021/8/16
*/
/**
* aliyun的OSS配置实例
*/
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AliyunOSSConfig {
/**
* oss参数:上传链接
*/
@JSONField(name="host")
private String host;
/**
* oss参数:accessKeyId
*/
@JSONField(name="access_key_id")
private String accessKeyId;
/**
* oss参数:文件路径
*/
@JSONField(name="file_path")
private String filePath;
/**
* oss参数:签名
*/
@JSONField(name="signature")
private String signature;
/**
* oss参数:策略
*/
@JSONField(name="policy")
private String policy;
/**
* bucket
*/
@JSONField(name="bucket")
private String bucket;
/**
* 目标文件夹,场景名
*/
@JSONField(name="folder_name")
private String folderName;
/**
* oss结果:文件完整URL
*/
@JSONField(name="file_url")
private String fileUrl;
}
aliyun的OSS签名配置实例
/**
* @description :
* @auther Tyler
* @date 2021/8/16
*/
import lombok.*;
/**
* aliyun的OSS签名配置实例
*/
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AliyunOSSSignConfig {
private String signature;
private String policy;
private String folderName;
}
aliyun的OSS配置实例
/**
* @description :
* @auther Tyler
* @date 2021/8/16
*/
import lombok.*;
/**
* aliyun的OSS配置实例
*/
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AliyunOSSWriteConfig {
private String bucket;
private String targetFileName;
private String folderName;
}
配置文件的实体
import lombok.Data;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* @description :
* @auther Tyler
* @date 2021/8/16
*/
@Component
@ConfigurationProperties(prefix = "aliyun")
@Data
public class BaseConfig {
private String mainDomain;
private String aliyunSmsSign;
private String aliyunSmsTemplet;
private Map<String,String> ossBucketMap;
private String ossEndpointValue;
private String ossEndpointInner;
private String ossAccessKeyId;
private String ossAccessKeySecret;
private String ossStsRegion;
private String ossStsSessionName;
private Integer ossStsExpire;
private String ossStsRoleId;
private String ossStsEndpoint;
private String ossStsAccessKeyId;
private String ossStsAccessKeySecret;
}
四,Service
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.tenyears.webCommon.config.oss.AliyunOSSSignConfig;
import com.tenyears.webCommon.config.oss.AliyunOSSWriteConfig;
import com.tenyears.webCommon.config.oss.BaseConfig;
import com.tenyears.webCommon.model.message.ResultMessage;
import com.tenyears.webCommon.service.service.OSSService;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.portable.ApplicationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
/**
* @description :
* @auther Tyler
* @date 2021/8/16
*/
@Service("ossService")
public class OSSImpl implements OSSService {
@Autowired
BaseConfig configBase;
/**
* 获取签名
* @param dir
* @return
* @throws Exception
*/
@Override
public AliyunOSSSignConfig generateSign(String dir) throws Exception {
// STS接入地址,例如sts.cn-hangzhou.aliyuncs.com。
String endpoint = configBase.getOssEndpointValue();
// 填写步骤1生成的访问密钥AccessKey ID和AccessKey Secret。
String accessKeyId = configBase.getOssAccessKeyId();
String accessKeySecret = configBase.getOssAccessKeySecret();
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
long expireTime = 300;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
// PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
String encodedPolicy = BinaryUtil.toBase64String(postPolicy.getBytes(StandardCharsets.UTF_8));
String postSignature = ossClient.calculatePostSignature(postPolicy);
AliyunOSSSignConfig config = new AliyunOSSSignConfig();
config.setPolicy(encodedPolicy);
config.setSignature(postSignature);
// respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
return config;
} catch (Throwable t) {
throw new Exception("oss generateSign " + t.getMessage());
} finally {
ossClient.shutdown();
}
}
/**
* 初始化config
* @param fileSence
* @param originFileName
* @return
* @throws Exception
*/
@Override
public AliyunOSSWriteConfig buildConfig(String fileSence, String originFileName) throws Exception {
// 获取bucketName
String bucketName = configBase.getOssBucketMap().get(fileSence);
AliyunOSSWriteConfig ob = new AliyunOSSWriteConfig();
ob.setFolderName(fileSence);
if (StringUtils.isNotBlank(originFileName)) {
ob.setTargetFileName(generateFileName(fileSence, originFileName));
}
ob.setBucket(bucketName);
return ob;
}
/**
* 生成文件名
* @param folder
* @param originFileName
* @return
*/
@Override
public String generateFileName(String folder, String originFileName) {
if (StringUtils.isNotBlank(originFileName)) {
//文件扩展类型
String extensionName = this.getExtensionName(originFileName);
//生成文件名
String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extensionName;
//文件路径
String filePath = getFilePath(folder, fileName);
return trimStart(filePath, "/");
}
return originFileName;
}
/**
* 根据文件夹和文件名生成文件路径
* * * @param folder 文件夹
* * @param fileName 文件名
* * @return 文件路径
*/
private static String getFilePath(String folder, String fileName) {
//文件路径
String filePath = StringUtils.EMPTY;
if (StringUtils.isNotBlank(folder)) {
String tempFolder = folder.replace(".", "");
tempFolder = trimStart(tempFolder, "/");
tempFolder = trimEnd(tempFolder, "/");
filePath = filePath + tempFolder + "/";
}
if (StringUtils.isNotBlank(fileName)) {
fileName = trimStart(fileName, "/");
filePath = filePath + fileName;
}
return filePath;
}
/**
* 获取文件的扩展名 * *
*
* @param fileName 文件名 *
* @return 扩展名
*/
private String getExtensionName(String fileName) {
if (StringUtils.isEmpty(fileName) || !fileName.contains(".")) {
return StringUtils.EMPTY;
}
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
/**
* 去除某个开头字符串 * *
*
* @param str 字符串
* @param symbol 开头字符串
* @return string
*/
private static String trimStart(String str, String symbol) {
if (StringUtils.isBlank(str) || StringUtils.isBlank(symbol)) {
return str;
}
str = str.trim();
if (StringUtils.isNotBlank(str) && str.startsWith(symbol)) {
return str.substring(symbol.length());
}
return str;
}
/**
* 去除某个结尾字符串
* * * @param str 字符串
* * @param symbol 结尾字符串
* * @return string
*/
private static String trimEnd(String str, String symbol) {
if (StringUtils.isBlank(str) || StringUtils.isBlank(symbol)) {
return str;
}
str = str.trim();
if (StringUtils.isNotBlank(str) && str.endsWith(symbol)) {
return str.substring(0, str.length() - symbol.length());
}
return str;
}
}
五,Controller
import com.tenyears.model.common.ApiRequest;
import com.tenyears.model.common.ApiResult;
import com.tenyears.webCommon.config.oss.*;
import com.tenyears.webCommon.service.service.OSSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* @description :
* @auther Tyler
* @date 2021/8/16
*/
/**
* oss 文件上传
*/
@RestController
@RequestMapping("api/oss")
public class OSSController {
@Autowired
OSSService manager;
@Autowired
BaseConfig configBase;
/**
* 获取场景和Bucket
* key : 场景 ,value : Bucket
* @return
*/
@RequestMapping(value = "get_oss_bucket_map", method = RequestMethod.POST)
public ApiResult<Map> get_oss_bucket_map()
{
ApiResult<Map> result=new ApiResult();
result.setCodeToSuccessed(configBase.getOssBucketMap());
return result;
}
/**
* 获取 oss token
*/
@RequestMapping(value = "get_oss_token", method = RequestMethod.POST)
public ApiResult<AliyunOSSConfig> getOssToken(@RequestBody ApiRequest<AliyunOssAutoSignRequest> request) throws Exception {
ApiResult<AliyunOSSConfig> result=new ApiResult<>();
AliyunOssAutoSignRequest reqData=request.getData();
AliyunOSSWriteConfig aliyunOSSWriteConfig = manager.buildConfig(reqData.getFileScene() ,reqData.getFileName());
AliyunOSSSignConfig signConfig = manager.generateSign(aliyunOSSWriteConfig.getFolderName());
AliyunOSSConfig config = new AliyunOSSConfig();
config.setBucket(aliyunOSSWriteConfig.getBucket());
config.setAccessKeyId(configBase.getOssAccessKeyId());
config.setFolderName(aliyunOSSWriteConfig.getFolderName());
config.setSignature(signConfig.getSignature());
config.setPolicy(signConfig.getPolicy());
config.setHost("https://" + config.getBucket() + "." + configBase.getOssEndpointValue());
config.setFilePath(manager.generateFileName(aliyunOSSWriteConfig.getFolderName(), request.getData().getFileName()));
config.setFileUrl(config.getHost() + "/" + config.getFilePath());
result.setCodeToSuccessed(config);
return result;
}
}
ApiRequest<T> 和 ApiResult<T> 就不展示了,以前文档有。
你们直接返回自己的实体对象