阿里云对象存储OSS并将URL地址的形式存储到数据库中

图片上传到阿里云 OSS,数据库只保存图片的 URL 地址(路径),这样既节省数据库空间,又利于后续管理和展示

所需阿里云依赖如下:

  <!-- 阿里云 Java SDK 核心库 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.0</version>
        </dependency>


        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>
package com.dy.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 阿里云配置实体类
 */
@Component
/*请注意,为了使用@ConfigurationProperties注解,你需要在Spring Boot应用程序中启用配置绑定功能。
你可以通过在主应用程序类上添加@EnableConfigurationProperties注解来实现。*/
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {

    private String endpoint; //表示OSS服务的访问域名。
    private String accessKeyId; //表示访问OSS服务所需的Access Key ID。
    private String accessKeySecret; //表示访问OSS服务所需的Access Key Secret。
    private String bucketName; //表示要操作的存储桶名称。

}
package com.dy.config;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

/**
 * AliOssUtil类是一个包含文件上传功能的工具类。
 */
@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实例。
        /*在upload方法中,首先创建了一个OSSClient实例,用于与OSS服务进行交互。*/
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            /*然后,通过调用ossClient.putObject方法将文件上传到指定的存储桶中。*/
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
            /*在上传过程中,通过捕获OSSException和ClientException来处理可能出现的异常情况,并输出相应的错误信息。*/
        } 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();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        /*最后,构建文件的访问路径,并使用日志记录上传文件的路径。*/
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

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

        return stringBuilder.toString();
    }
}

 业务代码如下:

 @Override
    public Result add(MultipartFile file, Integer articleId, String content){
        if(file == null ||  articleId == null || content == null){
            return Result.build(null, ResultCodeEnum.DATA_ERROR);
        }
        log.info("文件上传:",file);
        try {
            //原始文件名
            /*首先通过file.getOriginalFilename()获取原始文件名*/
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            /*然后通过originalFilename.lastIndexOf(".")获取文件名的后缀。*/
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            /*使用UUID.randomUUID().toString()生成一个随机的文件名,并将后缀拼接在文件名后面,构造出新的文件名。*/
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            /*然后,调用aliOssUtil.upload方法将文件上传到OSS,并获取文件的请求路径。*/
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            /*最后,返回一个Result对象,其中包含上传文件的请求路径。*/
            System.out.println("--------------------------------"+filePath);

            ArticleContent articleContent = new ArticleContent();
            articleContent.setArticleId(articleId);
            articleContent.setContent(content); //内容
            articleContent.setImages(filePath); //图片
           articleContent.setStatus(ArticleContentStatus.PENDING.getCode()); // 设置状态为待审核
            baseMapper.insert(articleContent);

        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
            return Result.fail();
        }
        return Result.ok();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值