SpringBoot使用阿里云OSS对象存储

一、引入依赖

<properties>
        <oss.version>2.8.3</oss.version>
    </properties>
<dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>${oss.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-codec</artifactId>
                    <groupId>commons-codec</groupId>
                </exclusion>
            </exclusions>
        </dependency>

二、配置阿里云OSS信息

# 阿里云OSS
  oss:
    endpoint: oss-cn-beijing.aliyuncs.com
    accessKeyId: LTAIkeA5QtdFvDiA
    accessKeySecret: xxxxxxxx
    bucket: xxxx
    templets-dir: qrcode
    images-dir: images

三、代码示例

public class ComplexComponent {
    private ComplexComponent() {}

    /**
     * 获取OSS的文件路径(不包括Host前缀)
     * @param dir 资源路径(images,templets)
     * @param filename 文件名称
     * @return OSS 文件路径
     */
    public static String getOssFilepath(String dir, String filename){
        StringBuilder sb = new StringBuilder();
        sb.append(dir)
                .append("/")
                .append(DateUtils.dateTime())
                .append("/")
                .append(IdUtils.fastSimpleUUID())
                .append("/")
                .append(filename);
        return sb.toString();
    }
}
@Component
@ConfigurationProperties(prefix = "oss")
public class OssUtils {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucket;
    private String templetsDir;
    private String imagesDir;
    private OssUtils(){ }

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint)
    {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId()
    {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId)
    {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret()
    {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret)
    {
        this.accessKeySecret = accessKeySecret;
    }

    public String getBucket()
    {
        return bucket;
    }

    public void setBucket(String bucket)
    {
        this.bucket = bucket;
    }

    public String getTempletsDir()
    {
        return templetsDir;
    }

    public void setTempletsDir(String templetsDir)
    {
        this.templetsDir = templetsDir;
    }

    public String getImagesDir()
    {
        return imagesDir;
    }

    public void setImagesDir(String imagesDir)
    {
        this.imagesDir = imagesDir;
    }

    private String getHost()
    {
        return "https://" + bucket + "." + endpoint;
    }

    private OSSClient getOssClient()
    {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 上传文件
     * @param filename 文件名 OSS fullPath 去掉host 前缀
     * @param inputStream 文件输入流
     * @return OSS fullPath
     */
    public String upload(String filename, InputStream inputStream)
    {
        if (Objects.isNull(filename) || Objects.isNull(inputStream))
        {
            return null;
        }
        OSSClient ossClient = getOssClient();
        ossClient.putObject(bucket, filename, inputStream);
        ossClient.shutdown();
        return getHost() + "/" + filename;
    }

    /**
     * 上传文件
     * @param filename 文件名 OSS fullPath 去掉host 前缀
     * @param file 文件
     * @return 上传后的OSS fullPath
     */
    public String upload(String filename, File file)
    {
        if (Objects.isNull(filename) || Objects.isNull(file))
        {
            return null;
        }
        OSSClient ossClient = getOssClient();
        ossClient.putObject(bucket, filename, file);
        ossClient.shutdown();
        return getHost() + "/" + filename;
    }

    /**
     * 下载文件并 返回输入流
     *
     * @param remoteFilename OSS 服务器 文件名称
     * @return 文件输入流
     */
    public InputStream download(String remoteFilename)
    {
        if (Objects.isNull(remoteFilename))
        {
            return null;
        }
        OSSClient ossClient = getOssClient();
        OSSObject ossObject = ossClient.getObject(bucket, remoteFilename);
        return ossObject.getObjectContent();
    }

    /**
     * 根据 OSS fullPath 下载文件
     * @param url OSS fullPath
     * @return 文件输入流
     */
    public InputStream downloadByUrl(String url)
    {
        if (Objects.isNull(url) || !url.startsWith(getHost()))
        {
            return null;
        }
        String key = url.substring(getHost().length() + 1);
        return this.download(key);
    }

    /**
     * 下载文件
     * @param url OSS fullPath
     * @param localFilename 本地文件名称
     */
    public void download(String url, String localFilename)
    {
        if (Objects.isNull(url) || !url.startsWith(getHost()))
        {
            return;
        }
        if (Objects.isNull(localFilename))
        {
            return;
        }
        File file = new File(localFilename);
        if (!file.getParentFile().exists())
        {
            file.getParentFile().mkdirs();
        }
        String key = url.substring(getHost().length() + 1);
        OSSClient ossClient = getOssClient();
        ossClient.getObject(new GetObjectRequest(bucket, key), file);
        ossClient.shutdown();
    }

    /**
     * 根据全路径获取文件路径
     *
     * @param path OSS fullPath
     * @return 去掉OSS host 的suffix
     */
    public String getFilename(String path)
    {
        String host = this.getHost();
        if (Objects.isNull(path) || !path.startsWith(host))
        {
            return null;
        }
        return path.substring(host.length() + 1);
    }
}

四、上传接口

@RestController
@RequestMapping("/aliyun/oss")
public class AliyunOssController {
 @Autowired
    private OssUtils ossUtils;
     @PostMapping("/upload")
    @ApiOperation("上传")
    @ApiImplicitParam(name = "file",value = "文件",dataType = "MultipartFile",dataTypeClass = MultipartFile.class)
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
     String ossPath ;
    if (file == null || file.isEmpty()) {
            return AjaxResult.error("文件内容为空");
        }
        InputStream is = new FileInputStream(file);
           ossPath =  ossUtils.upload(ossFilename, is);
    }
    return AjaxResult.success().put("url", ossPath);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值