SpringBoot项目整合阿里云OSS对象储存

一、阿里云账号管理获取AccessKey在这里插入图片描述
在这里插入图片描述
连接地址:https://ram.console.aliyun.com/manage/ak

二、导入依赖

<!-- 阿里OSS -->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.3</version>
</dependency>

<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

<!-- spring-boot -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
三、配置yml文件

获取bucketName 和 endpoint地址 在对象存储填写你自己创建的

地址:https://oss.console.aliyun.com/在这里插入图片描述

server:
  port: 80
ali:
  access-key: 你自己的key
  access-key-secret: 你自己的key
  bucket-name: 你自己的key-yan
  endpoint: http://oss-cn-chengdu.aliyuncs.com
四、编写上传删除文件方法

使用@ConfigurationProperties读取配置文件

/**
 * @author wy
 * @since  2020/9/22
 */
@Data
@Component
@ConfigurationProperties(prefix = "ali")
public class OssConfigurationProperties {

    // bucket
    private String bucketName;

    // 域名 oss-cn-chengdu.aliyuncs.com
    private String endpoint;

    // accessKeyId
    private String accessKey;

    // accessKeySecret
    private String accessKeySecret;


    // 文件上传
    public boolean upload(String filePath, String url) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        try {
            // 上传文件流。
            InputStream inputStream = new FileInputStream(filePath);
            client.putObject(bucketName, url, inputStream);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭OSSClient。
            client.shutdown();
        }
    }
    // 重载upload
    public boolean upload(InputStream is, String url) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        try {
            // 上传文件流。
            client.putObject(bucketName, url, is);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭OSSClient。
            client.shutdown();
        }
    }


    // 删除文件
    public boolean delFile(String path) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        String[] split = path.split("/");
        String[] newPath = Arrays.copyOfRange(split, 3, split.length);
        StringBuilder ossPath = new StringBuilder();
        for (int i = 0; i < newPath.length; i++) {
            if (i == newPath.length - 1)
                ossPath.append(newPath[i]);
            else
                ossPath.append(newPath[i]).append("/");
        }
        try {
            client.deleteObject(bucketName, ossPath.toString());
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            client.shutdown();
        }
    }


    // 获取文件路径
    public String getFileOSSUrl(String url) {
        String prefix = "https://";
        return prefix + bucketName + "." + endpoint.substring(7) + "/" +url;
    }

}

FileUtil.java一个文件工具类

public class FileUtil {

	/* connect path (include filename) */
	public static String concatAllPath(String... pathList) {
		StringBuilder path = new StringBuilder();
		for (int i = 0; i < pathList.length; i++) {
			if (i != 0) {
				path.append("/").append(pathList[i]);
			} else {
				path.append(pathList[i]);
			}
		}
		return path.toString();
	}

	// 获取文件后缀名
	public static String createUuIdName(MultipartFile file) {
		String saveFileName = file.getOriginalFilename();
		// 获取后缀名
		String[] strArray = saveFileName.split("\\.");
		int suffixIndex = strArray.length - 1;
		String exe = strArray[suffixIndex];
		return UUID.randomUUID().toString().replaceAll("-", "") + "." + exe;
	}
}

五、编写controller

/**
 * @author wy
 * @since  2020/9/22
 */
@RestController
@RequestMapping("/file")
public class UploadController {

    @Resource
    private OssConfigurationProperties configurationProperties;

    /**
     *上传文件
     * @param file 文件
     * @param dir 文件夹
     * @return 返回阿里访问全地址
     */
    @PostMapping("/upload")
    @SneakyThrows
    public List<String> uploadFiles(MultipartFile[] file, String dir) {
        List<String> ossUrls = new ArrayList<>();
        for (MultipartFile f : file) {
            String url = FileUtil.concatAllPath(dir, FileUtil.createUuIdName(f));
            // 上传到oss服务器
            boolean upload = configurationProperties.upload(f.getInputStream(), url);
            if (upload) {// 上传oss服务器成功
                // 获取文件路径
                String ossURL = configurationProperties.getFileOSSUrl(url);
                ossUrls.add(ossURL);
            }
        }
        return ossUrls;
    }

    @DeleteMapping("/del")
    public Boolean uploadFiles(String path) {
        return configurationProperties.delFile(path);
    }


}

六、测试在这里插入图片描述
删除:删除文件需要把文件地址作为参数即可

gitee源码地址:https://gitee.com/wyaoao/spring-boot-oss.git

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值