使用阿里云OSS对象存储系统创建AliossUtil工具类实现图片上传功能

1.去阿里云服务获取OSS存储服务

创建bucket库具体流程可以参考官方文档:

https://help.aliyun.com/zh/oss/developer-reference/sdk-code-samples/?spm=a2c4g.11186623.0.0.574971cfdGtecS

2.导入阿里云jar包

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

3.编写工具类代码

package com.zstwd.utils;

import com.aliyun.oss.ClientException;

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

import org.springframework.stereotype.Component;


import java.io.ByteArrayInputStream;



@Slf4j
@Component
public class AliOssUtil {

//使用自己的api密钥
    private final String endpoint="";

    private final String accessKeyId="";

    private final String accessKeySecret="";

    private final 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.编写控制层代码

package com.zstwd.controller;

import com.zstwd.entity.vo.Result;
import com.zstwd.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AliOssUtil aliOssUtil;

//@RequestParam("image") 是否加这个注解根据前端业务进行修改
    @PostMapping
    public Result  upload(@RequestParam("image") MultipartFile file) {
        // 获取原文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 构造新的文件名
        String newFilename = UUID.randomUUID().toString() + substring;
        try {
            String filePath =aliOssUtil.upload(file.getBytes(), newFilename);
            return Result.success(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(500, "上传失败");
        }

    }
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值