首页 > 编程技术 > java

Springboot集成阿里云OSS上传文件系统教程

发布时间:2021-6-29 00:01

第一步:开通阿里云OSS服务,创建Bucket,获取id和密钥

第二步:根据官方文档编写上传代码

1.新建maven项目
添加依赖:

<!-- 阿里云oss依赖 -->
 <dependency>
 <groupId>com.aliyun.oss</groupId>
 <artifactId>aliyun-sdk-oss</artifactId>
 </dependency>
 <!-- 日期工具栏依赖 -->
 <dependency>
 <groupId>joda-time</groupId>
 <artifactId>joda-time</artifactId>
 </dependency>

2.配置application.properties

#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev

#阿里云 OSS
#不同的服务器,地址不同  需要根据自己的信息填写
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=guli-file

3、创建启动类

创建OssApplication.java

package com.sun.oss;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.sun"})
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}

启动报错:

多模块应用时,该模块没有使用数据库,配置文件中没有数据库配置信息,则会报错
第一种方法:
在配置类中添加数据库配置信息:

# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/musicdb?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

第二种方法:添加注解,在@SpringBootApplication注解上加上exclude,解除自动加载DataSourceAutoConfiguration

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

4.编写一个工具类:
用于读取配置文件密钥信息
ConstantPropertiesUtils.java

//当项目已启动,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;

    //定义公开静态常量
    public static String END_POIND;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POIND = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}

5.编写controller类

@Api(description = "头像上传到oss")
@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin//解决跨域问题
public class OssController {

    @Autowired
    private OssService ossService;

    //上传头像的方法
    @ApiOperation("上传头像")
    @PostMapping
    public R uploadOssFile(MultipartFile file) {
        //获取上传文件  MultipartFile
        //返回上传到oss的路径
        String url = ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    }
}

6.编写service类

@Service
public class OssServiceImpl implements OssService {
    //上传头像
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //工具类获取值
        String endPoind = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try {
            //创建Oss实例
            OSS ossClient = new OSSClientBuilder().build(endPoind, accessKeyId, accessKeySecret);

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();

            //1.防止上传文件名重复,使用UUid
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //拼接fileName
            filename=uuid+filename;

            //2.把文件按照日期分类
            //获取当前日期,需要引入org.joda.time依赖
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            filename=datePath+"/"+filename;

            //调用oss方法实现上传
            //第一个参数 Bucket名称
            //第二个参数 上传到oss的文件路径和文件名
            //第三个参数 上传文件输入流
            ossClient.putObject(bucketName,filename,inputStream);

            //关闭OssClient
            ossClient.shutdown();

            //上传之后把文件路劲返回
            //需要把上传到oss路径手动拼接出来
            //https://edu-975.oss-cn-beijing.aliyuncs.com/07aef13af7ea82703f3eb320c3f577ec.jpg
            String url="https://"+bucketName+"."+endPoind+"/"+filename;
            return url;


        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}

解决上传文件大小:

# 单个文件大小
spring.servlet.multipart.max-request-size=10MB
# 单次最大文件
spring.servlet.multipart.max-file-size=3MB

swagger测试运行:

成功!!

到此这篇关于Springboot集成阿里云OSS上传文件系统教程的文章就介绍到这了,更多相关Springboot集成阿里云oss文件上传内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: