spring boot整合oss对象存储服务

该文章介绍了如何在SpringBoot项目中集成阿里云OSS服务,包括在pom.xml中添加依赖,配置application.yml文件,创建OSSClient,以及编写Controller层的文件上传和下载功能。同时,文章还展示了前端页面用于文件上传的表单和已上传文件的列表展示。
摘要由CSDN通过智能技术生成

阿里云官方网址:阿里云-计算,为了无法计算的价值

选择对象存储oss并且开通服务,在控制台创建一个OSS bucket

2代码部分

1、首先创建一个springboot项目

2、在pom.xml中导入maven的依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.0</version>
</dependency>

3、编写配置文件application.yml

aliyun:
  oss:
    endpoint: yuor-endpoint
		access-key-id: your-keyId
		access-key-secret: your-keySecret
		bucket-name: your-bucketname

4、写一个配置类

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Yt
 * @date 2023/7/10
 */
@Configuration
public class OSSConfiguration {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    
    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;


    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    //创建一个OSSClient实例。
    @Bean
    public OSS ossClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
}

5、controller层

package com.ruoyi.web.controller.aliyunoss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.ruoyi.system.service.OSSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Yt
 * @date 2023/7/10
 */
@Controller
@RequestMapping("/system/oss")
public class FileController {
    @Autowired
    private OSS ossClient;
    @Autowired
    private OSSService ossService;

    @GetMapping()
    public String openOss(Model model) {
        List<String> fileNames = ossService.getFileNames();
        model.addAttribute("fileNames", fileNames);
        return "/system/oss/ossFile";
    }
	//上传文件
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        ossClient.putObject("captionyt", fileName, file.getInputStream());
        return "redirect:/system/image/images";
    }
	//下载文件
    @GetMapping("/download/{fileName}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String fileName) {
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build("yourendpoint", "yourkeyID", "yourkeySecret");
        // 获取文件内容
        OSSObject object = ossClient.getObject("bucketname", fileName);
        InputStream inputStream = object.getObjectContent();
        // 构建响应头
        HttpHeaders headers = new HttpHeaders();
        try {
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8")
                    .replaceAll("\\+", "%20")
                    .replaceAll("\\*", "%2A")
                    .replaceAll("%7E", "~");
            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 创建响应实体
        ResponseEntity<InputStreamResource> responseEntity = ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(inputStream));

        // 关闭OSS客户端
        ossClient.shutdown();
        return responseEntity;
    }
}

5、service层(只写出实现类)

package com.ruoyi.system.service.impl;

import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.ruoyi.system.service.OSSService;
import org.springframework.stereotype.Service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectListing;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Yt
 * @date 2023/7/11
 */
@Service
public class OSSServiceImpl implements OSSService {
    private static final String endpoint = "endpoint";
    private static final String accessKeyId = "accessKeyId";
    private static final String accessKeySecret = "accessKeySecret";
    private static final String bucketName = "bucketname";
    @Override
    public List<String> getFileNames() {
        List<String> fileNames = new ArrayList<>();
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 获取文件列表
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName));
            List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
            // 提取文件名
            for (OSSObjectSummary objectSummary : objectSummaries) {
                fileNames.add(objectSummary.getKey());
            }
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
        return fileNames;
    }
}

前端页面部分

<!DOCTYPE html>
<!--suppress ALL-->

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>File Upload</title>
</head>
<body>
<form action="/system/oss/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>

<hr>

<h2>Files:</h2>
<ul>
    <li th:each="fileName : ${fileNames}">
        <a th:href="@{/system/oss/download/{fileName}(fileName=${fileName})}" th:text="${fileName}"></a>
    </li>
</ul>
</body>
</html>

上述涉及到到endpoint、accessKeyId、accessKeySecret、bucketname需要替换为自己的

如果没有自己的AcceccKey的话需要创建一个

验证之后会创建一个新的ACcessKey

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值