(IDEA编辑器)SpringBoot+Maven+myBatisPlus项目 实现图片上传到 阿里云 OSS云存储
一、对象存储OSS首先到阿里云注册(https://account.aliyun.com/),尽量用支付宝登录,因为方便实名认证。1、开通“对象存储OSS”服务(1)申请阿里云账号 (2)实名认证 (3)开通“对象存储OSS”服务 (4)进入管理控制台2、创建Bucket 选择:标准存储、公共读、不开通3、创建RAM子用户二、使用SDK先看下文档使用:OSS我这里是用来上传头像的,单独写的一个模块
一、对象存储OSS
首先到阿里云注册(https://account.aliyun.com/),尽量用支付宝登录,因为方便实名认证。
1、开通“对象存储OSS”服务
(1)申请阿里云账号 (2)实名认证 (3)开通“对象存储OSS”服务 (4)进入管理控制台
2、创建Bucket 选择:标准存储、公共读、不开通
3、创建RAM子用户
二、使用SDK
先看下文档使用:
OSS我这里是用来上传头像的,单独写的一个模块
oss模块具体文件有哪些文件,图片展示:
pom文件:
<?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">
<parent>
<artifactId>service</artifactId>
<groupId>com.xy</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service_oss</artifactId>
<!-- 你们只需要看这里面需要引入的,上面是模块配置信息 -->
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!--aliyunOSS 阿里云存储-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.1.0</version>
</dependency>
<!--日期时间工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
</project>
配置文件bootstrap.properties:
注意:在网上下载Nacos服务,并启动,然后把访问地址和端口号配置,启动的时候有显示
#nacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#nacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#环境设置:dev、test、prod
spring.profiles.active=dev
#阿里云 OSS
#不同的服务器,地址不同
#你的阿里云创建的 地域节点
aliyun.oss.file.endpoint=your endpoint
##你的阿里云创建的 AccessKeyId
aliyun.oss.file.keyid=your accessKeyId
##你的阿里云创建的 AccessKeySecret
aliyun.oss.file.keysecret=your accessKeySecret
##你的阿里云创建Bucket的时候的名称 bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=bucketName
配置文件图片示意图:
控制层OssController:
package com.atguigu.oss.controller;
import com.atguigu.commonutils.result.R;
import com.atguigu.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@CrossOrigin //支持跨域
@RequestMapping("/eduoss/fileoss")
public class OssController {
@Autowired
private OssService ossService;
//上传头像的方法
@PostMapping
//public R uploadOssFile(MultipartFile file){
public String uploadOssFile(MultipartFile file){
//获取上传文件 MultipartFile
String url = ossService.uploadFileAvatar(file);
//我这里封装了一个编码返回类,暂时不显示了,简单改了一下
//return R.ok().data("url", url);
return url;
}
}
工具类ConstantPropertiesUtils:
package com.atguigu.oss.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//当项目已启动,spring接口,spring加载之后,执行接口一个方法
@Component
public class ConstantPropertiesUtils implements InitializingBean {
//读取配置文件内容
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
//因为属性是private私有 implements InitializingBean
//定义公开静态常量
public static String END_POIND;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
public static String FILE_HOST;
@Override
public void afterPropertiesSet() throws Exception {
END_POIND = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
接口OssService:
package com.atguigu.oss.service;
import org.springframework.web.multipart.MultipartFile;
public interface OssService {
//上传文件到oss
String uploadFileAvatar(MultipartFile file);
}
实现 OssServiceImpl:
package com.atguigu.oss.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;
@Service
public class OssServiceImpl implements OssService {
//上传头像到oss
@Override
public String uploadFileAvatar(MultipartFile file) {
//通过工具类获取配置信息
// Endpoint以上海为例,其它Region请按实际情况填写。
String endpoint = ConstantPropertiesUtils.END_POIND;
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketname = ConstantPropertiesUtils.BUCKET_NAME;
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 获取上传文件流
InputStream inputStream = file.getInputStream();
文件名:uuid.扩展名
String original = file.getOriginalFilename();
//在文件名称里面添加随机唯一的值
String fileName = UUID.randomUUID().toString();
String fileType = original.substring(original.lastIndexOf("."));
String newName = fileName + fileType;
//把文件按照日期进行分类
//获取当前日期
String datePath = new DateTime().toString("yyyy/MM/dd");
//拼接路径
fileName = datePath +"/"+ newName;
//调用oss方法实现上传
//第一个参数 Bucket 名称, 第二个参数 上传到oss文件路径和文件名称
ossClient.putObject(bucketname, fileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//把上传之后文件路径返回
//需要把上传到阿里云oss路径手动拼接出来
String url = "https://"+ bucketname +"."+ endpoint +"/"+ fileName;
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
启动类OssApplication:
package com.atguigu.oss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
//启动 OSS阿里云
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //因为此模块只是上传头像,所有用不到数据库,所以在启动的时候需要在启动类配置这个配置
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.atguigu"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}
为了减少使用时的错误,我把父项目的pom也显示出来,因为OSS是单独模块,可能有些依赖没引入会导致无法使用或报错,如果是因为依赖问题,那大家对照先pom自己试一下少哪些依赖或者百度也可以:
首先我把完整的模块分布情况以图片的形式展示出来:
然后最外层父项目pom依赖展示:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xy</groupId>
<artifactId>guli_parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>guli_parent</name>
<!-- 添加 pom类型 -->
<packaging>pom</packaging>
<description>Demo project for Spring Boot</description>
<modules>
<module>service</module>
<module>common</module>
</modules>
<!-- FIXME change it to the project's website -->
<url>http://maven.apache.org/</url>
<inceptionYear>2001</inceptionYear>
<distributionManagement>
<site>
<id>website</id>
<url>scp://webhost.company.com/www/website</url>
</site>
</distributionManagement>
<!--统一管理jar包版本-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<lombok.version>1.2.17</lombok.version>
<log4j.version>1.16.18</log4j.version>
<mysql.version>5.1.47</mysql.version>
<druid.version>1.1.16</druid.version>
<mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
<mybatisPlus.version>3.0.5</mybatisPlus.version>
<ojdbc6.version>11.2.0.4.0</ojdbc6.version>
<swagger2.version>2.9.2</swagger2.version>
<swaggerui.version>2.9.2</swaggerui.version>
<ioswagger.version>1.5.21</ioswagger.version>
<slf4j.version>1.7.25</slf4j.version>
<jodatime.version>2.10.1</jodatime.version>
</properties>
<!--子模块继承之后,提供作用:锁定版本+子module不用写groupId和version-->
<dependencyManagement>
<dependencies>
<!--swagger需要的相关依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swaggerui.version}</version>
</dependency>
<!--修复 swagger 进入时报错 For input string: ""-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${ioswagger.version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${ioswagger.version}</version>
</dependency>
<!--swagger需要的相关依赖结束-->
<!--日期时间工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime.version}</version>
</dependency>
<!--apache.maven-->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</dependency>
<!--spring boot 2.2.2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud Hoxton.SR1-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring cloud 阿里巴巴 2.1.0.RELEASE-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<!--ojdbc6-->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${ojdbc6.version}</version>
</dependency>
<!-- druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.spring.boot.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisPlus.version}</version>
</dependency>
<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>repository.springframework.maven.release</id>
<name>Spring Framework Maven Release Repository</name>
<url>http://maven.springframework.org/milestone/</url>
</repository>
<repository>
<id>org.springframework</id>
<url> http://maven.springframework.org/snapshot</url>
</repository>
<repository>
<id>spring-milestone</id>
<name>Spring Maven MILESTONE Repository</name>
<url>http://repo.spring.io/libs-milestone</url>
</repository>
<repository>
<id>spring-release</id>
<name>Spring Maven RELEASE Repository</name>
<url>http://repo.spring.io/libs-release</url>
</repository>
</repositories>
</project>
service模块工程pom依赖展示:
<?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">
<parent>
<artifactId>guli_parent</artifactId>
<groupId>com.xy</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service</artifactId>
<packaging>pom</packaging>
<modules>
<module>service_edu</module>
<module>service_vod</module>
<module>service_oss</module>
</modules>
<dependencies>
<!--引入其他模块下的service_base Swagger的使用-->
<dependency>
<groupId>com.xy</groupId>
<artifactId>service_base</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--因为在service_base已经引入过这个模块了,所以这里就不需要引入了-->
<!--引入common_utils R类公共返回方法的使用-->
<!--<dependency>
<groupId>com.xy</groupId>
<artifactId>common_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>-->
<!--JSONArray -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- nacos config-->
<!--<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>-->
<!-- SpringCloud ailibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud ailibaba sentinel-->
<!--<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>-->
<!--<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--监控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!--统一访问路径 http://localhost:8001/swagger-ui.html 端口号是启动服务设置的-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
</dependencies>
</project>
最后一步,我这使用了swagger测试:
我配置的swagger2,它是一个规范和完整的框架,用于生成、描述、调用和可视化Restful风格的web服务,使用spring boot 整合它,至于怎么使用上网搜一下,配置方法,这里就不详谈了。
进入swagger(统一访问路径 http://localhost:端口号/swagger-ui.html 端口号是配置文件里 启动服务 设置的)
查看阿里云OSS:
以上为个人笔记,仅供参考~
更多推荐
所有评论(0)