SpringBoot如何集成aliyunOSS并上传文件

1、导入阿里云OSS配置

在Maven工程中使用OSS Java SDK,只需在pom.xml中加入相应依赖即可。以3.15.1版本为例,在<dependencies>中加入如下内容:

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

如果使用的是Java 9及以上的版本,则需要添加jaxb相关依赖。添加jaxb相关依赖示例代码如下:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.3</version>
</dependency>

2、读取OSS配置

#阿里云oss配置
aliyun:
  oss:
    endpoint: 
    access-key-id: 
    access-key-secret: 
    bucket-name: 
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {

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

}

3、创建阿里云OSS工具类

@Data
@AllArgsConstructor
@Slf4j
public class AliyunOSSUntil {

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

    public  String upload(MultipartFile file) throws IOException {

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));

        //获取文件输入流
        InputStream inputStream = file.getInputStream();

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

        //上传文件
        try {

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,filename, inputStream);

            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        }
        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();
            }
        }
        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + filename;

        return url;

    }
}

4、创建配置类,用于创建AliOssUtil对象

@Configuration
public class AliyunOSSConfiguration {

    private final Logger log = LoggerFactory.getLogger(AliyunOSSConfiguration.class);

    @Bean
    @ConditionalOnMissingBean
    public AliyunOSSUntil aliyunOSSUntil(AliyunOssProperties aliyunOssProperties){

        log.info("开始创建阿里云OSS工具类对象:{}",aliyunOssProperties);
        return new AliyunOSSUntil(aliyunOssProperties.getEndpoint(),
                aliyunOssProperties.getAccessKeyId(),
                aliyunOssProperties.getAccessKeySecret(),
                aliyunOssProperties.getBucketName());
    }
}

5、创建文件上传控制类


@RestController
public class UploadController {

    private final Logger log = LoggerFactory.getLogger(UploadController.class);
    private AliyunOSSUntil aliyunOSSUntil;

    @Autowired
    public UploadController(AliyunOSSUntil aliyunOSSUntil) {
        this.aliyunOSSUntil = aliyunOSSUntil;
    }

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        try{
            String url = aliyunOSSUntil.upload(file);
            return Result.success(url);
        } catch (IOException e) {
            log.info("文件上传失败");
        }
        
        return Result.error("文件上传失败");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值