SpringBoot中OSS文件存储(阿里云篇)

SpringBoot中OSS文件存储(阿里云篇)

在现代Web应用开发中,文件存储是一个常见需求。阿里云的对象存储服务(OSS)提供了一种高效、安全的文件存储解决方案。本文将介绍如何在SpringBoot项目中集成阿里云OSS,实现文件的上传和访问。

在这里插入图片描述

一、pom文件配置

在Maven包管理下添加对应的OSS坐标

            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>${aliyun.sdk.oss}</version>
            </dependency>

二、yml文件中写入配置项:

在项目的yml配置文件中添加阿里云OSS的相关配置项。

  #本地配置
  alioss:
    endpoint: oss-cn-beijing.aliyuncs.com
    access-key-id: your-access-key-id
    access-key-secret: your-access-key-secret
    bucket-name: your-bucket-name

或者在全局配置中引用环境变量:

  #全局配置
test:
#本项目默认名称为test
  alioss:
    endpoint: ${sky.alioss.endpoint}
    access-key-id: ${sky.alioss.access-key-id}
    access-key-secret: ${sky.alioss.access-key-secret}
    bucket-name: ${sky.alioss.bucket-name}

三、写配置类:

为了方便在代码中使用yml中的配置,我们需要创建一个配置类,将yml中的配置项导入到Spring的上下文中。

@Component
@ConfigurationProperties(prefix = "test.alioss")
//导入了yml配置文件的属性
@Data
public class AliOssProperties {

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

}

四、写工具类:

接下来,我们创建一个工具类,封装文件上传到OSS的逻辑。

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

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

/**

  • 文件上传

  • @param bytes

  • @param objectName

  • @return
    */
    public String upload(byte[] bytes, String objectName) {

    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    try {
    // 创建PutObject请求。
    ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
    } catch (OSSException oe) {
    System.out.println("Caught an OSSException, which means your request made it to OSS, "
    + “but was rejected with an error response for some reason.”);
    System.out.println(“Error Message:” + oe.getErrorMessage());
    System.out.println(“Error Code:” + oe.getErrorCode());
    System.out.println(“Request ID:” + oe.getRequestId());
    System.out.println(“Host ID:” + oe.getHostId());
    } catch (ClientException ce) {
    System.out.println("Caught an ClientException, which means the client encountered "
    + "a serious internal problem while trying to communicate with OSS, "
    + “such as not being able to access the network.”);
    System.out.println(“Error Message:” + ce.getMessage());
    } finally {
    if (ossClient != null) {
    ossClient.shutdown();
    }
    }

    //文件访问路径规则
    StringBuilder stringBuilder = new StringBuilder(“https://”);
    stringBuilder
    .append(bucketName)
    .append(“.”)
    .append(endpoint)
    .append(“/”)
    .append(objectName);

    log.info(“文件上传到:{}”, stringBuilder.toString());

    return stringBuilder.toString();
    }
    }
    五、写上传接口:

我们编写一个RESTful接口用于文件上传,并调用工具类进行文件上传操作。

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传:{}",file);

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}

以上步骤完成后,SpringBoot项目就集成了阿里云OSS文件存储功能。通过这些配置和代码,我们可以方便地将文件上传到阿里云OSS,并生成可访问的URL,供前端使用。
}
return Result.error(MessageConstant.UPLOAD_FAILED);
}
}

以上步骤完成后,SpringBoot项目就集成了阿里云OSS文件存储功能。通过这些配置和代码,我们可以方便地将文件上传到阿里云OSS,并生成可访问的URL,供前端使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值