目录:
- 开通阿里云OSS
- pom依赖
- 配置文件
- 配置类
- Service层
- Controller层
开通阿里云OSS
登录阿里云官网,搜索“OSS”关键字,进入 OSS 产品页。
如果是 OSS 新用户的话,可以享受 6 个月的新人专享优惠价,不过续费的时候还是会肉疼。
进入 OSS 管理控制台,点击「Bucket 列表」,点击「创建 Bucket」。
Bucket 的词面意思是桶,这里指存储空间,就是用于存储对象的容器。注意读写权限为“公共读”,也就是允许互联网用户访问云空间上的图片。
pom依赖
<!-- 阿里云 OSS -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
配置文件
aliyun:
oss:
# oss对外服务的访问域名
endpoint: oss-cn-beijing.aliyuncs.com
# 访问身份验证中用到用户标识
accessKeyId: LTAI5
# 用户用于加密签名字符串和oss用来验证签名字符串的密钥
accessKeySecret: RYN
# oss的存储空间
bucketName: itwanger-oss1
# 上传文件大小(M)
maxSize: 3
# 上传文件夹路径前缀
dir:
prefix: codingmore/images/
配置类
@Configuration
public class OssClientConfig {
@Value("${aliyun.oss.endpoint}")
String endpoint ;
@Value("${aliyun.oss.accessKeyId}")
String accessKeyId ;
@Value("${aliyun.oss.accessKeySecret}")
String accessKeySecret;
@Bean
public OSSClient createOssClient() {
return (OSSClient)new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
Service层
上传文件到逻辑实现,返回文件保存路径
@Service
public class OssServiceImpl implements IOssService{
@Value("${aliyun.oss.maxSize}")
private int maxSize;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@Value("${aliyun.oss.dir.prefix}")
private String dirPrefix;
@Autowired
private OSSClient ossClient;
@Override
public String upload(MultipartFile file) {
try {
return upload(file.getInputStream(), file.getOriginalFilename());
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
return null;
}
@Override
public String upload(InputStream inputStream,String name) {
String objectName = getBucketName(name);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
return formatPath(objectName);
}
private String getBucketName(String url){
String ext = "";
for(String extItem:imageExtension){
if(url.indexOf(extItem) != -1){
ext = extItem;
break;
}
}
return dirPrefix+ DateUtil.today()+"/"+ IdUtil.randomUUID()+ext;
}
private String formatPath(String objectName){
return "https://" +bucketName+"."+ ossClient.getEndpoint().getHost() + "/" + objectName;
}
/**
外链图片上传
*/
public String upload(String url) {
String objectName = getFileName(url);
try (InputStream inputStream = new URL(url).openStream()) {
ossClient.putObject(bucketName, objectName, inputStream);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
return formatOSSPath(objectName);
}
}
Controller层
返回文件保存路径.
@Controller
@RequestMapping("/ossController")
public class OssController {
@Autowired
private IOssService ossService;
@RequestMapping(value = "/upload",method=RequestMethod.POST)
@ResponseBody
public ResultObject<String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
return ResultObject.success(ossService.upload(file));
}
}