谷粒 | 10 | 阿里雲OSS存儲對象服務


阿里雲OSS對象存儲服務

准備工作

1、在service模塊新建子模塊service_oss

2、引入pom.xml文件中引入oss服務依賴

 <dependencies>
        <!--aliyunOSS-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
        </dependency>

        <!-- 日期工具欄依賴   -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>

    </dependencies>

后台上傳開發

1、在配置文件application.properties中配置阿里雲

#服務端口
server.port=8003
#服務名
spring.application.name=service-oss

#環境設置:dev、test、prod
spring.profiles.active=dev

# nacos服務地址
#spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

#阿里雲 OSS
#不同的服務器,地址不同
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI4GFzTBo3LTCyo1wLA1Ys
aliyun.oss.file.keysecret=EAcieIxjX84Yr3TCvXX3LG95JNSWnS
#bucket可以在控制台創建,也可以使用java代碼創建
aliyun.oss.file.bucketname=edu-bi

2、啟動類配置

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan(basePackages = {"com.birdy"})
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class);
    }
}

exclude = DataSourceAutoConfiguration.class: 排除數據源配置

因為oss模塊不需要操作數據庫,所以在application.properties配置文件中沒有配置數據庫,但springboot是自動加載配置,沒有找到數據庫配置,啟動時會報錯

Failed to configure a DataSource:' url’ attribute is not specif: 未能配置DataSource:“URL”屬性不是指定:

Reason: Failed to determine a suitable driver class 原因:未能確定合適的驅動程序類

3、定義工具類獲取配置中的數據

@Component
public class ConstantPropertiesUtils implements InitializingBean {

    //讀取配置文件內容
    @Value("${aliyun.oss.file.endpoint}")
    private String endPoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    //定義公開靜態常量
    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;
    
	/*
		屬性初始化完成后執行該方法
	*/
    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endPoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}

由於私有屬性外界無法訪問,所以要定義公共靜態常量並將私有屬性值賦給這些常量,才能被其他類獲取

4、創建服務層接口和實現類

//service層接口
public interface OssService {
    String uploadFileAvatar(MultipartFile file);
}
package com.birdy.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.birdy.oss.service.OssService;
import com.birdy.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

//實現類
@Service
public class OssServiceImpl implements OssService {
    //上傳頭像到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 工具類獲取值
        String endPoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            // 1、創建OSS實例。
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

            // 2、獲取上傳文件輸入流
            InputStream inputStream = file.getInputStream();

            // 3、獲取文件名稱
            String fileName = file.getOriginalFilename();

            //在文件名稱里面添加隨機值,避免文件重名,同時替換掉文件名中的"-"
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            // yuy76t5rew01.jpg
            fileName = uuid+fileName;

            //把文件按照日期進行分類
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //  2019/11/12/ewtqr313401.jpg
            fileName = datePath+"/"+fileName;

            /*
             4、調用oss方法實現上傳
         	   第一個參數  Bucket名稱
         	   第二個參數  上傳到oss文件路徑和文件名稱   aa/bb/1.jpg
           	   第三個參數  上傳文件輸入流
            */
            ossClient.putObject(bucketName , fileName , inputStream);

            // 5、關閉OSSClient。
            ossClient.shutdown();

            //返回上傳之后文件路徑
            //需要手動拼接上傳到阿里雲oss的路徑
            // https://edu-birdy.oss-cn-beijing.aliyuncs.com/gitlab頭像.jpg
            String url = "https://"+bucketName+"."+endPoint+"/"+fileName;
            return url;
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

5、控制層調用

@RestController
@RequestMapping("/eduoss/fileoss")
public class OssController {
    @Autowired(required = false)
    private OssService ossService;
    //上傳頭像的方法
    @PostMapping
    public Result uploadOssFile(MultipartFile file) {
        //獲取上傳文件  MultipartFile
        //返回上傳到oss的路徑
        String url = ossService.uploadFileAvatar(file);
        return Result.ok().data("url",url);
    }
}

前端整合上傳頭像

准備

config文件夾下的dev.env.js文件中添加nginx代理端口

 'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  // BASE_API: '"https://easy-mock.com/mock/5950a2419adc231f356a6636/vue-admin"',
  BASE_API: '"http://localhost:9001"',
  OSS_PATH: '"https://guli-file.oss-cn-beijing.aliyuncs.com"'
})

1、導入組件模板

在組件模板中導入上傳頭像組件ImageCropperPanThumbvue-admin-template后台管理模板精簡版沒有該組件,完整版有,本次使用的是精簡版,需要從完成版拷過來)

2、引入模板組件

<script>
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'

export default {
  components: {ImageCropper, PanThumb}
}
</script>

3、使用

<el-form-item label="講師頭像">

    <!-- 使用PanThumb組件,頭銜縮略圖 -->
    <pan-thumb :image="teacher.avatar"/>
    <!-- 文件上傳按鈕 -->
    <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更換頭像
    </el-button>

       <!--
      v-show:是否顯示上傳組件
      :key:類似於id,如果一個頁面多個圖片上傳控件,可以做區分
      :url:后台上傳的url地址
      @close:關閉上傳組件
      @crop-upload-success:上傳成功后的回調 
        <input type="file" name="file"/>
      -->
    <image-cropper
                   v-show="imagecropperShow"
                   :width="300"
                   :height="300"
                   :key="imagecropperKey"
                   :url="BASE_API+'/eduoss/fileoss'"
                   field="file"
                   @close="close"
                   @crop-upload-success="cropSuccess"/>
	</el-form-item>

      <el-form-item>
    <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
</el-form-item>

export default {
  components: {ImageCropper, PanThumb},
  data() {
    return {
      teacher:{
        name: '',
        sort: 0,
        level: 1,
        career: '',
        intro: '',
        avatar: ''
      },

      //上傳彈框組件是否顯示
      imagecropperShow:false,
      imagecropperKey:0,//上傳組件key值
      BASE_API:process.env.BASE_API, //獲取dev.env.js里面地址
      saveBtnDisabled:false  // 保存按鈕是否禁用,
    }
  },
  methods:{
    close() { //關閉上傳彈框的方法
        this.imagecropperShow=false
        //上傳組件初始化
        this.imagecropperKey = this.imag,cropperKey+1
    },
    //上傳成功方法
    cropSuccess(data) {
      this.imagecropperShow=false
      //上傳之后接口返回圖片地址
      this.teacher.avatar = data.url
      this.imagecropperKey = this.imagecropperKey+1
    }
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM