图片存储阿里云oss

阿里云oss存储

在开发中我们很经常遇见需要上传图片的功能,图片上传功能开发简单,但问题是我们一般把图片存在到哪里呢?

有下面几种解决方案
1.直接将图片保存到服务的硬盘

  1. 优点:开发简捷,成本低
  2. 缺点:扩容难

2.使用分布式文件系统进行存储(比如fastDfs)

  1. 优点:容易实现扩容
  2. 缺点:开发复杂度稍大(尤其是开发复杂的功能)

3.使用nfs做存储(没操作过)

  1. 优点:开发较为便捷
  2. 缺点:需要有一定的运维知识进行部署和维护

4.使用第三方的存储服务

  1. 优点:开发简单,拥有强大功能,免维护
  2. 缺点:付费

今天要练习的就是第四个,第三方存储服务(阿里云oss存储管理)
当然需要钱对吗,但还好不贵,为了技术白嫖不了啦哈哈哈。
在这里插入图片描述
购买自行操作吧我就跳过了。

开始使用oss

创建Bucket

使用OSS,首先需要创建Bucket,Bucket翻译成中文是水桶的意思,把存储的图片资源看做是水,想要盛水必须得有桶,就是这个意思了。

在这里插入图片描述
创建完bucket后然后选择bucket后就能看到url、消耗流量等
在这里插入图片描述

管理文件

创建一个maven工程并引入依赖如下:

引入依赖

  <!--spring boot的支持-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
    </parent>
    <dependencies>
        <!--springboot的web支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

    </dependencies>

编写aliyun.properties配置文件

aliyun.endpoint = oss-cn-beijing.aliyuncs.com<youEndpoint>
aliyun.accessKeyId = <youAccesskeyId>
aliyun.accessKeySecret = <youAccesskeySecret>
aliyun.bucketName = test-xxja<youBucketName>
aliyun.urlPrefix = http://test-xxja.oss-cn-beijing.aliyuncs.com/ <youUrlprefix>

编写PicUploadResult

package com.xxja.oss.vo;
import lombok.Data;

@Data
public class PicUploadResult {
    // 文件唯一标识
    private String uid;
    // 文件名
    private String name;
    // 状态有:uploading done error removed
    private String status;
    // 服务端响应内容,如:'{"status": "success"}'
    private String response;
}

编写AliyunConfig

package com.xxja.oss.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = {"classpath:aliyun.properties"})
@ConfigurationProperties(prefix = "aliyun")
@Data
public class AliyunConfig {

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

    @Bean
    public OSS oSSClient() {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }
}

编写service

package com.xxja.oss.service;

import com.aliyun.oss.OSS;
import com.xxja.oss.config.AliyunConfig;
import com.xxja.oss.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class PicUploadService {
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;

    public PicUploadResult upload(MultipartFile uploadFile) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        // 封装Result对象,并且将文件的byte数组放置到result对象中
        PicUploadResult fileUploadResult = new PicUploadResult();
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        // 上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    /**
     * 文件路径
     * @param sourceFileName
     * @return
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "image/" + dateTime.toString("yyyy")
                + "/"+dateTime.toString("MM")+"/" +
                dateTime.toString("dd") + "/" +
                System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");

    }
}

编写controller

package com.xxja.oss.controller;

import com.xxja.oss.service.PicUploadService;
import com.xxja.oss.vo.PicUploadResult;
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;

@RequestMapping("pic/upload")
@RestController
public class PicUploadController {
    @Autowired
    private PicUploadService picUploadService;

    @PostMapping
    public PicUploadResult upload(@RequestParam("file") MultipartFile uploadFile) {
        return this.picUploadService.upload(uploadFile);
    }
}

编写启动类

package com.xxja.oss;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OssTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssTestApplication.class, args);
    }
}

启动
使用postman访问

在这里插入图片描述
上传成功。
访问路径
在这里插入图片描述
这出现了一个问题。就是访问路径的时候是下载
点击详情。保留一个最新的把其他的都删了
在这里插入图片描述
默认是image/jpeg,改为image/jpg
在这里插入图片描述
访问路径为
https://test-xxja.oss-cn-beijing.aliyuncs.com/image/2020/12/29/16092302557854125.jpg
注意是https不是http哦
在这里插入图片描述ok,访问成功,简单就是需要钱吧。再接再厉加油!!!

  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值