【阿里OSS文件上传】SpringBoot实现阿里OSS对象上传

1. YAML配置阿里OSS属性

  alioss:
    endpoint: oss-cn-beijing.aliyuncs.com
    access-key-id: L***e
    access-key-secret: j***X
    bucket-name: c***i

2. 设置对象保存OSS属性

注册为Component方便后续直接调用。

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

@Component
@ConfigurationProperties(prefix = "alioss")
@Data
public class AliOssProperties {

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

}

3. 阿里OSS文件上传工具类Util

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;

@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();
            }
        }

        //文件访问路径规则 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();
    }
}

4. 将工具类配置为Bean,并填充OSS属性

import com.sky.properties.AliOssProperties;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class OssConfiguration {

    @Bean
    // 确保只会有一个Bean
    @ConditionalOnMissingBean
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties) {
        log.info("注册阿里OSSBean");
        return new AliOssUtil(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKeyId()
                , aliOssProperties.getAccessKeySecret(), aliOssProperties.getBucketName());
    }
}

5. 使用

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

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

    @Resource
    AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public Result<String> upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileURL = aliOssUtil.upload(file.getBytes(), UUID.randomUUID().toString() + extension);
            return Result.success(fileURL);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
  • 21
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SpringBoot可以通过阿里云的OSS(Object Storage Service)实现文件,以下是实现步骤: 1. 引入阿里云OSS SDK依赖 在pom.xml中引入以下依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency> ``` 2. 配置OSS连接信息 在application.properties文件中配置OSS连接信息: ```properties oss.endpoint=your-endpoint oss.accessKeyId=your-access-key-id oss.accessKeySecret=your-access-key-secret oss.bucketName=your-bucket-name ``` 3. 创建OSS客户端 在配置类中创建OSS客户端: ```java @Configuration public class OSSConfiguration { @Value("${oss.endpoint}") private String endpoint; @Value("${oss.accessKeyId}") private String accessKeyId; @Value("${oss.accessKeySecret}") private String accessKeySecret; @Bean public OSSClient ossClient() { return new OSSClient(endpoint, accessKeyId, accessKeySecret); } } ``` 4. 实现接口 ```java @RestController public class UploadController { @Autowired private OSSClient ossClient; @Value("${oss.bucketName}") private String bucketName; @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); try { ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes())); return "success"; } catch (IOException e) { e.printStackTrace(); } finally { ossClient.shutdown(); } return "fail"; } } ``` 以上就是通过阿里云OSS实现文件的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CRE_MO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值