来吧,展示!SpringBoot OSS 整合全过程,没见过比这更详细的了
前言
阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。其数据设计持久性不低于 99.9999999999%(12 个 9),服务设计可用性(或业务连续性)不低于 99.995%。
OSS 具有与平台无关的 RESTful API 接口,您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。
您可以使用阿里云提供的 API、SDK 接口或者 OSS 迁移工具轻松地将海量数据移入或移出阿里云 OSS。数据存储到阿里云 OSS 以后,您可以选择标准存储(Standard)作为移动应用、大型网站、图片分享或热点音视频的主要存储方式,也可以选择成本更低、存储期限更长的低频访问存储(Infrequent Access)和归档存储(Archive)作为不经常访问数据的存储方式。
登录阿里云,进入到控制台
点击确定,就建好了。
- 接下来就开始附代码
新建一个springboot项目
导入依赖 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SpringOOS</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>2.3.0.RELEASE</version>
</dependency>
<!-- OSS SDK 相关依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
</project>
application.yml
## aliyun oss
## 配置说明参考: com.ljq.demo.springboot.common.config.OSSConfig.class
oss:
endpoint: oss-cn-shenzhen.aliyuncs.com
url: https://oos-all.oss-cn-shenzhen.aliyuncs.com/
accessKeyId: #这里在个人中心里accesskeys查看
accessKeySecret: #这里在个人中心里accesskeys查看
bucketName: #这里写OSS里自己创建的OSS文件夹
写一个config配置类
package com.sykj.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.io.Serializable;
/**
* @Description: 阿里云 OSS 配置信息
* @Author: jiangpengcheng
* @Date: 2020/07/15
*/
@Data
@Configuration
public class OSSConfig implements Serializable {
private static final long serialVersionUID = -119396871324982279L;
/**
* 阿里云 oss 站点
*/
@Value("${oss.endpoint}")
private String endpoint;
/**
* 阿里云 oss 资源访问 url
*/
@Value("${oss.url}")
private String url;
/**
* 阿里云 oss 公钥
*/
@Value("${oss.accessKeyId}")
private String accessKeyId;
/**
* 阿里云 oss 私钥
*/
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
/**
* 阿里云 oss 文件根目录
*/
@Value("${oss.bucketName}")
private String bucketName;
}
工具类
package com.sykj.util;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.sykj.config.OSSConfig;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
/**
* @Description: 阿里云 oss 上传工具类(高依赖版)
* @Author: @author jiangpengcheng
* @Date: 2020/7/15
*/
public class OSSBootUtil {
private OSSBootUtil(){}
/**
* oss 工具客户端
*/
private volatile static OSSClient ossClient = null;
/**
* 上传文件至阿里云 OSS
* 文件上传成功,返回文件完整访问路径
* 文件上传失败,返回 null
* @author jiangpengcheng
* @param ossConfig oss 配置信息
* @param file 待上传文件
* @param fileDir 文件保存目录
* @return oss 中的相对文件路径
*/
public static String upload(OSSConfig ossConfig, MultipartFile file, String fileDir){
initOSS(ossConfig);
StringBuilder fileUrl = new StringBuilder();
try {
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
String fileName = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0,18) + suffix;
if (!fileDir.endsWith("/")) {
fileDir = fileDir.concat("/");
}
fileUrl = fileUrl.append(fileDir + fileName);
System.out.println(fileUrl+"-----------------");
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("image/jpg");
ossClient.putObject(ossConfig.getBucketName(), fileUrl.toString(), file.getInputStream(),objectMetadata);
} catch (IOException e) {
e.printStackTrace();
return null;
}
fileUrl = fileUrl.insert(0,ossConfig.getUrl());
return fileUrl.toString();
}
/**
* 初始化 oss 客户端
* @param ossConfig
* @return
*/
private static OSSClient initOSS(OSSConfig ossConfig) {
if (ossClient == null ) {
synchronized (OSSBootUtil.class) {
if (ossClient == null) {
ossClient = new OSSClient(ossConfig.getEndpoint(),
new DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()),
new ClientConfiguration());
}
}
}
return ossClient;
}
/**
* 根据前台传过来的文件地址 删除文件
* @author jiangpengcheng
* @param objectName
* @param ossConfig
* @return
*/
public static ResponseResult delete(String objectName,OSSConfig ossConfig) {
initOSS(ossConfig);
//将完整路径替换成 文件地址 因为yml里的url有了地址链接https: //oos-all.oss-cn-shenzhen.aliyuncs.com/
// 如果再加上地址 那么又拼接了 所以删除不了 要先把地址替换为 jpc/2020-07-16/1594857669731-51d057b0-9778-4aed.png
String fileName = objectName.replace("https://oos-all.oss-cn-shenzhen.aliyuncs.com/", "");
System.out.println(fileName+"******************************");
// 根据BucketName,objectName删除文件
ossClient.deleteObject(ossConfig.getBucketName(), fileName);
return ResponseResult.ok("删除成功",fileName);
}
}
数据返回工具类
package com.sykj.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @ClassName ResponseResult
* @Description TODO
* Author JiangPengCheng
* Date 2020/7/15 9:13
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult implements Serializable {
private Integer code;
private String message;
private Object object;
public static ResponseResult ok(String message){
return new ResponseResult(200,message,null);
}
public static ResponseResult ok(String message, Object object){
return new ResponseResult(200,message,object);
}
public static ResponseResult error(String message){
return new ResponseResult(500,message,null);
}
public static ResponseResult error(String message, Object o){
return new ResponseResult(500,message,o);
}
}
Service类
package com.sykj.service;
import com.sykj.util.ResponseResult;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
/**
* @Description: 公共业务
* @Author: junqiang.lu
* @Date: 2018/12/24
*/
public interface CommonService {
/**
* 上传文件至阿里云 oss
*
* @param file
* @param
* @return
* @throws Exception
*/
ResponseResult uploadOSS(MultipartFile file) throws Exception;
ResponseResult delete(String objectName);
}
Service实现类
package com.sykj.service.impl;
import com.sykj.config.OSSConfig;
import com.sykj.service.CommonService;
import com.sykj.util.OSSBootUtil;
import com.sykj.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: 公共业务具体实现类
* @Author: junqiang.lu
* @Date: 2018/12/24
*/
@Service("commonService")
public class CommonServiceImpl implements CommonService {
@Autowired
private OSSConfig ossConfig;
/**
* 上传文件至阿里云 oss
*
* @param file
* @param
* @return
* @throws Exception
*/
@Override
public ResponseResult uploadOSS(MultipartFile file) throws Exception {
// 格式化时间
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(new Date());
// 高依赖版本 oss 上传工具
String ossFileUrlBoot = null;
/**
* ossConfig 配置类
* file 文件
* "jpc/"+format 上传文件地址 加时间戳
*/
ossFileUrlBoot = OSSBootUtil.upload(ossConfig, file, "jpc/"+format);
System.out.println(ossFileUrlBoot);
Map<String, Object> resultMap = new HashMap<>(16);
// resultMap.put("ossFileUrlSingle", ossFileUrlSingle);
resultMap.put("ossFileUrlBoot", ossFileUrlBoot);
return ResponseResult.ok("上传成功~~",ossFileUrlBoot);
}
@Override
public ResponseResult delete(String objectName) {
ResponseResult delete = OSSBootUtil.delete(objectName, ossConfig);
return delete;
}
}
Controller类
package com.sykj.comtroller;
import com.sun.org.apache.regexp.internal.RE;
import com.sykj.service.CommonService;
import com.sykj.util.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* @Description: 公共模块控制中心
* @Author: junqiang.lu
* @Date: 2018/12/24
*/
@RestController
@RequestMapping("api/demo/common")
public class CommonController {
private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
@Autowired
private CommonService commonService;
/**
* 上传文件至阿里云 oss
*
* @param file
* @param
* @return
* @throws Exception
*/
@RequestMapping(value = "/upload/oss", method = {RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseResult uploadOSS(@RequestParam(value = "file") MultipartFile file) throws Exception {
System.out.println(file.getInputStream());
// ResponseResult responseResult = commonService.uploadOSS(file);
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return ResponseResult.ok("ok");
}
@RequestMapping("/delete/oss")
public ResponseResult deltetOss(String objectName){
System.out.println(objectName+"-------------------------------");
ResponseResult delete = commonService.delete(objectName);
return delete;
}
}
注意postman选择file
这样就完成了
最后
感谢你看到这里,看完有什么的不懂的可以在评论区问我,觉得文章对你有帮助的话记得给我点个赞,每天都会分享java相关技术文章或行业资讯,欢迎大家关注和转发文章!
来吧,展示!SpringBoot OSS 整合全过程,没见过比这更详细的了的更多相关文章
- springboot+layui 整合百度富文本编辑器ueditor入门使用教程(踩过的坑)
springboot+layui 整合百度富文本编辑器ueditor入门使用教程(踩过的坑) 写在前面: 富文本编辑器,Multi-function Text Editor, 简称 MTE, 是一 ...
- SpringBoot Druid整合,SpringBoot 集成Druid
SpringBoot Druid整合,SpringBoot 集成Druid ================================ ©Copyright 蕃薯耀 2018年4月8日 http ...
- SpringBoot RabbitMQ 整合使用
 ### 前提 上次写了篇文章,[<SpringBoot ...
- 学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用
学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用 一.SpringBoot系列教程 二.SpringBoot ...
- Redis的安装、基本使用以及与SpringBoot的整合
1.概述 Redis 是现在很流行的一个 NoSql 数据库,每秒读取可以达到10万次,能够将数据持久化,支持多种数据结构,容灾性强,易扩展,常用于项目的缓存中间件. 今天我们就来聊聊关于Redis的 ...
- 使用VUE+SpringBoot+EasyExcel 整合导入导出数据
使用VUE+SpringBoot+EasyExcel 整合导入导出数据 创建一个普通的maven项目即可 项目目录结构 1 前端 存放在resources/static 下 index.html &l ...
- SpringBoot+Mybatis-Plus整合Sharding-JDBC5.1.1实现单库分表【全网最新】
一.前言 小编最近一直在研究关于分库分表的东西,前几天docker安装了mycat实现了分库分表,但是都在说mycat的bug很多.很多人还是倾向于shardingsphere,其实他是一个全家桶,有 ...
- SpringBoot 同时整合thymeleaf html、vue html和jsp
问题描述 SpringBoot如何同时访问html和jsp SpringBoot访问html页面可以,访问jsp页面报错 SpringBoot如何同时整合thymeleaf html.vue html ...
- SpringBoot+AOP整合
SpringBoot+AOP整合 https://blog.csdn.net/lmb55/article/details/82470388 https://www.cnblogs.com/onlyma ...
随机推荐
- JS里各种类型的循环
for... for( 初始条件; 判断条件; 递增条件 ) { ... } for ... in 可以把一个对象里面的所有属性依次循环出来 var person = { name: 'Jack', ...
- abstract关键字的说法
含有abstract修饰符的class即为抽象类,abstract 类不能创建的实例对象.含有abstract方法的类必须定义为abstract class,abstract class类中的方法不必 ...
- OpenCV(c++)-1 安装和配置OpenCV4.4(Windows+visual studio 2019)
@ 目录 安装OpenCV4 在Windows系统安装OpenCV4 配置visual studio 2019 配置包含路径 验证配置结果 安装OpenCV4 OpenCV是一个基于BSD许可(开源) ...
- elasticsearch启动报错
1,max file descriptors [4096] for elasticsearch process is too low, increase to at least [65536] 查看 ...
- 使用Socket通信(一)
使用socket需要一个服务器,我用的是tomcat,好像AS不支持Tomcat了,还有什么好的服务器求推荐,使用Tomcat去官网下载,然后还要安装Java的jdk,然后配置jak环境变量,然后配置 ...
- 定位流之z-index属性
1.固定定位是脱离标准流的,不会占用标准流的空间 2.和绝对定位有点像,也不区分行内块级元素 3.类似于前面学的背景关联方式(让某个背景图片不随滚动而滚动)让某个元素不随着滚动条的滚动而滚动 ie6不 ...
- day81:luffy:课程分类页面&课程信息页面&指定分类显示课程信息&分页显示课程信息
目录 1.构建课程前端初始页面 2.course后端的准备工作 3.后端实现课程分类列表接口 4.前端发送请求-获取课程分类信息 5.后端实现课程列表信息的接口 6.前端显示列表课程信息 7.按照指定 ...
- think PHP5.1使用时 session重定向丢失问题
查了很多资料,也看了redirect底层代码,具体来说,还是多个用的地方不太对.做个笔记防忘记: 遇重定向后丢失session时: 1.php.ini配置文件,不要自动启动,默认是0,session. ...
- JDK 8 新增的 LongAdder,得过来看一下
前言 在介绍 AtomicInteger 时,已经说明在高并发下大量线程去竞争更新同一个原子变量时,因为只有一个线程能够更新成功,其他的线程在竞争失败后,只能一直循环,不断的进行 CAS 尝试,从而浪 ...
- 重磅解读:K8s Cluster Autoscaler模块及对应华为云插件Deep Dive
摘要:本文将解密K8s Cluster Autoscaler模块的架构和代码的Deep Dive,及K8s Cluster Autoscaler 华为云插件. 背景信息 基于业务团队(Cloud BU ...