使用SpringBoot和OSS实现图片的上传、下载和删除功能

11 篇文章 0 订阅
1 篇文章 0 订阅

数据准备

在阿里云申请一个账号,开通对象存储功能,创建一个桶,详细步骤可参考阿里云官方文档

https://help.aliyun.com/product/31815.html?spm=5176.8465980.0.dexternal.c0fa14503jckqF

我已经在对象存储控制台创建了一个桶miaomiao,如下图所示:

本博文重点讲述使用springboot对OSS的访问

创建springboot

我们使用idea快速创建一个springboot项目,引入oss相关依赖。JDK版本为8

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lagou</groupId>
    <artifactId>oss</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>oss</name>
    <description>阿里云对象存储</description>

    <properties>
        <java.version>8</java.version>
    </properties>

    <dependencies>
        <!--springboot 测试支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

创建配置文件aliyun.properties

aliyun.properties用于存储阿里云的配置文件

aliyun.endpoint=http://oss-cn-beijing.aliyuncs.com
aliyun.accessKeyId=shuaige  #请从自己阿里云获取
aliyun.accessKeySecret=meilve  #请从自己阿里云获取
aliyun.bucketName=miamiaobucket
aliyun.urlPrefix=http://miamiaobucket.oss-cn-beijing.aliyuncs.com

关键类

项目架构如下图所示

Aliconfig 

package com.lagou.oss.config;

import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * <p>Title: 阿里云配置类</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: http://www.ubisys.com.cn/</p>
 *
 * @Auther: cw
 * @Date: 2020/9/3 20:34
 */
@Configuration
@PropertySource("classpath:aliyun.properties")
@ConfigurationProperties(prefix = "aliyun")
@Data
public class Aliconfig {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String urlPrefix;

    @Bean
    public OSSClient oSSClient() {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }


}

FileUpLoadService

package com.lagou.oss.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.lagou.oss.config.Aliconfig;
import com.lagou.oss.vo.FileUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * <p>Title: 文件上传服务类</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: http://www.ubisys.com.cn/</p>
 *
 * @Auther: cw
 * @Date: 2020/9/3 20:43
 */
@Service
public class FileUpLoadService {

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};
    @Autowired
    private OSS ossClient;
    @Autowired
    private Aliconfig aliyunConfig;

    /**
     *  文件上传
     * @param uploadFile
     * @return
     */
    public FileUploadResult upload(MultipartFile uploadFile) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                break;
            }
        }
        //封装Result对象,并且将文件的byte数组放置到result对象中
        FileUploadResult fileUploadResult = new FileUploadResult();
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        //文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // 上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        fileUploadResult.setStatus("done");
        fileUploadResult.setResponse("success");
        //this.aliyunConfig.getUrlPrefix() + filePath 文件路径需要保存到数据库
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    /**
     *  通过源文件获取 路径和文件名
     * @param sourceFileName
     * @return
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    /**
     * 查看文件列表
     * @return
     */
    public List<OSSObjectSummary> list() {
        // 设置最大个数。
        final int maxKeys = 200;
        // 列举文件。
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    /**
     * @desc 删除文件
     */
    public FileUploadResult delete(String objectName) {
        // 根据BucketName,objectName删除文件
        ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);
        FileUploadResult fileUploadResult = new FileUploadResult();
        fileUploadResult.setName(objectName);
        fileUploadResult.setStatus("removed");
        fileUploadResult.setResponse("success");
        return fileUploadResult;
    }

    /**
     *   下载文件
     * @param os
     * @param objectName
     * @throws IOException
     */
    public void exportOssFile(OutputStream os, String objectName) throws IOException {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
        // 读取文件内容。
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int lenght = 0;
        while ((lenght = in.read(buffer)) != -1) {
            out.write(buffer, 0, lenght);
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
}

FileUploadResult

package com.lagou.oss.vo;

import lombok.Data;

/**
 * <p>Title: 阿里云oss通用结果返回类 </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: http://www.ubisys.com.cn/</p>
 *
 * @Auther: cw
 * @Date: 2020/9/3 20:41
 */
@Data
public class FileUploadResult {


    // 文件唯一标识
    private String uid;
    // 文件名
    private String name;
    // 状态有:uploading done error removed
    private String status;
    // 服务端响应内容,如:'{"status": "success"}'
    private String response;

}

FileUploadController

package com.lagou.oss.controller;

import com.aliyun.oss.model.OSSObjectSummary;
import com.lagou.oss.service.FileUpLoadService;
import com.lagou.oss.vo.FileUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>Title:阿里云oss存储 controller </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: http://www.ubisys.com.cn/</p>
 *
 * @Auther: cw
 * @Date: 2020/9/4 21:31
 */
@Controller
public class FileUploadController {

    @Autowired
    private FileUpLoadService fileUploadService;


    /**
     * 文件上传到oss
     * @param uploadFile
     * @return
     * @throws Exception
     */
    @RequestMapping("file/upload")
    @ResponseBody
    public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
            throws Exception {
        return fileUploadService.upload(uploadFile);
    }

    /**
     * 根据文件名删除
     * @param objectName
     * @return
     * @throws Exception
     */
    @RequestMapping("file/delete")
    @ResponseBody
    public FileUploadResult delete(@RequestParam("fileName") String objectName)
            throws Exception {
        return fileUploadService.delete(objectName);
    }


    /**
     *  查看桶内所有文件
     * @return
     * @throws Exception
     */
    @RequestMapping("file/list")
    @ResponseBody
    public List<OSSObjectSummary> list()
            throws Exception {
        return fileUploadService.list();
    }

    /**
     *  根据文件名进行下载
     * @param objectName
     * @param response
     * @throws IOException
     */
    @RequestMapping("file/download")
    @ResponseBody
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        fileUploadService.exportOssFile(response.getOutputStream(),objectName);
    }


}

测试

文件上传

获取文件列表

文件下载

文件删除

具体的请求,下载源码,在源码的classpath下有postman的请求json

源码地址

https://gitee.com/yulanzhilian.com/lagouphasefourmodulefouthcode/blob/master/README.md

 

 

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中集成阿里云对象存储服务(OSS),可以按照以下步骤进行: 1. 添加Maven或Gradle依赖: 对于Maven项目,可以在`pom.xml`文件中添加如下依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.13.3</version> </dependency> ``` 对于Gradle项目,可以在`build.gradle`文件的`dependencies`部分添加如下依赖: ```groovy implementation 'com.aliyun.oss:aliyun-sdk-oss:3.13.3' ``` 2. 配置阿里云OSS的AccessKey、SecretKey和Endpoint: 在`application.properties`文件中添加以下配置: ```properties spring: aliyun: access-key: <your-access-key> secret-key: <your-secret-key> oss: endpoint: <your-endpoint> bucket-name: <your-bucket-name> ``` 替换上述配置中的`<your-access-key>`、`<your-secret-key>`、`<your-endpoint>`和`<your-bucket-name>`分别为你的AccessKey、SecretKey、OSS Endpoint和Bucket名称。 3. 创建OSS客户端Bean: 在你的Spring Boot应用程序的配置类(例如,标记有`@SpringBootApplication`注解的类)中添加如下Bean定义: ```java 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; @Configuration public class OSSConfig { @Value("${spring.aliyun.access-key}") private String accessKey; @Value("${spring.aliyun.secret-key}") private String secretKey; @Value("${spring.aliyun.oss.endpoint}") private String endpoint; @Bean public OSS ossClient() { return new OSSClientBuilder().build(endpoint, accessKey, secretKey); } } ``` 4. 使用OSS客户端进行操作: 在需要使用OSS服务的地方注入`OSS`对象,并调用相应的方法进行操作,例如上传文件、删除文件等。 这样,你就可以在Spring Boot中成功集成阿里云OSS了。希望对你有帮助!如果你有其他问题,可以继续提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值