Java简单的阿里云对象存储OSS文件上传工具类

阿里云对象存储OSS文件上传工具类

使用的依赖包

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.6.2</version>
</dependency>
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.6.0</version>
</dependency>

工具类代码如下

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description 阿里云对象存储上传工具类
 * @Author oldwei
 * @Date 2019/9/28 12:19
 * @Version 2.0
 */
public class AliyunOssUtil {

    public Map<String, String> uploadFile(MultipartFile file) {
        //上传文件
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String uuid = RandomUtil.randomString(32);
        // 文件路径
        String objectName = "oldweipro/project/" + DateUtil.today() + "/" + uuid + suffix;
        // 以下信息在阿里云控制台查找
        String accessKeyId = "xxxxxxxxx";
        String accessKeySecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
        String bucketName = "atx-hik";
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String domain = "https://oss.oldwei.com/";
        Map<String, String> map = new HashMap<>(2);
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传Byte数组。
            byte[] content = file.getBytes();
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
            // 关闭OSSClient。
            ossClient.shutdown();
            map.put("domain", domain);
            map.put("objectName", objectName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
posted @   老卫同学  阅读(634)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示
主题色彩