阿里云--云存储OSS

云存储OSS申请步骤和我上一篇短信一致

依赖

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

application.yml

server:
  port: 8130
spring:
  application:
    name: service-oss
aliyun:
  oss:
    endpoint: oss-cn-beijing.aliyuncs.com
    accessKeyId: XXXXX
    secret: XXXXXXX
    bucket: XXXXXX  #Bucket 名称

config

package com.lizheng.config;

import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author 笑起来和猫是似的先生
 * @ClassName OssProperties
 * @description: TODO
 * @datetime 2023年 08月 03日 11:12
 * @version: 1.0
 */
@Data
@Component
public class OssProperties implements InitializingBean {

    @Value("${aliyun.oss.endpoint}")
    private  String endpoint;//站点
    @Value("${aliyun.oss.accessKeyId}")
    private  String accessKeyId;//管理的key
    @Value("${aliyun.oss.secret}")
    private  String secret;//密钥
    @Value("${aliyun.oss.bucket}")
    private  String bucket;//节点 目录


    public static   String END_POINT;//站点

    public static   String ACCESS_KEY_ID;//管理的key

    public static   String KEY_SECRET;//密钥

    public static   String BUCKET_NAME;//节点 目录




    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT=endpoint;
        ACCESS_KEY_ID=accessKeyId;
        KEY_SECRET=secret;
        BUCKET_NAME=bucket;
    }
}
package com.lizheng.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author 笑起来和猫似的先生
 * @ClassName SwaggerConfig
 * @description: TODO
 * @datetime 2023年 08月 01日 18:46
 * @version: 1.0
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket creatRestapi(){
        return new Docket(DocumentationType.SWAGGER_2).
                pathMapping("/").
                select().apis(RequestHandlerSelectors.basePackage("com.lizheng")).
                paths(PathSelectors.any()).
                build().apiInfo(new ApiInfoBuilder().title("SpringBoot整合Swagger").description("上班用").
                        version("1.0").contact(new Contact("lizheng","http://www.lizheng.com","lizheng@163.com")).
                        license("The Apache license").licenseUrl("http://www.lizheng.com").build());
    }
}

controller

package com.lizheng.controller;

import com.lizheng.exception.BusinessException;
import com.lizheng.result.ResponseEnum;
import com.lizheng.result.Result;
import com.lizheng.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author 笑起来和猫似的先生
 * @ClassName FileController
 * @description: TODO
 * @datetime 2023年 08月 03日 11:09
 * @version: 1.0
 */
@Api(tags = "阿里云OSS 对象存储")
@RestController
@RequestMapping("/api/oss/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(
            @ApiParam(value = "文件",required = true)
            @RequestParam("file")MultipartFile file,
            @ApiParam(value = "模块",required = true)
            @RequestParam( "module") String module
            ){
        try {
            InputStream inputStream = file.getInputStream();
            //获取原始文件名
            String originalFilename= file.getOriginalFilename();
            //上传
            String url = fileService.upload(inputStream,module,originalFilename);

            //上传成功
            return Result.ok().message("上传成功了").data("url",url);
        }catch (Exception ex){
            ex.printStackTrace();
            try {
                throw new BusinessException(ResponseEnum.UPLOAD_ERROR,ex.getMessage());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
    @ApiOperation("文件删除")
    @DeleteMapping("/remove")
    public Result remove(
            @ApiParam(value = "要删除的文件的路径",required = true)
            @RequestParam("url") String url
    ){
        fileService.removeFile(url);
        return Result.ok().message("删除成功");
    }

}

service 

package com.lizheng.service;

import java.io.InputStream;

/**
 * @author 笑起来和猫似的先生
 * @ClassName FileService
 * @description: TODO
 * @datetime 2023年 08月 03日 11:09
 * @version: 1.0
 */

public interface FileService {
    //上传
    String upload(InputStream inputStream, String module, String filename);
     //删除
    void removeFile(String url);
}

serviceImpl

package com.lizheng.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lizheng.config.OssProperties;
import com.lizheng.service.FileService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author 笑起来和猫似的先生
 * @ClassName FileServiceImpl
 * @description: TODO
 * @datetime 2023年 08月 03日 11:10
 * @version: 1.0
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String filename) {
        OSS ossClient = new OSSClientBuilder().build(OssProperties.END_POINT, OssProperties.ACCESS_KEY_ID, OssProperties.KEY_SECRET);
        // 创建OSS客户端对象,使用OssProperties中的配置参数

        // 生成日期路径,格式为yyyy/MM/dd
        String timeFolder = new DateTime().toString("yyyy/MM/dd");

        // 文件名处理:在原始文件名基础上生成一个唯一的UUID并保留文件扩展名
        filename = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));

        // 构建OSS对象的存储路径,格式为module/日期路径/文件名
        String key = module + "/" + timeFolder + "/" + filename;

        // 将输入流上传到OSS指定的Bucket中,使用生成的存储路径作为文件的唯一标识
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);

        // 关闭OSS客户端连接
        if (ossClient != null) {
            ossClient.shutdown();
        }

        // 返回上传后的文件URL,格式为https://Bucket名称.Endpoint/存储路径
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.END_POINT + "/" + key;
    }

    @Override
    public void removeFile(String url) {
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(OssProperties.END_POINT,OssProperties.ACCESS_KEY_ID,OssProperties.KEY_SECRET);
        String host = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.END_POINT + "/";
        String objectName = url.substring(host.length());

        ossClient.deleteObject(OssProperties.BUCKET_NAME,objectName);
        if (ossClient!=null){
            ossClient.shutdown();
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值