阿里云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
}
}

最新文章

  1. ASP.NET Core 1.1.0 Release Notes
  2. 自建git node pm2 (不赘述,就说遇见的问题)
  3. 替换jenkins上打包完成的安装包的方法
  4. 多线程java的concurrent用法详解(转载)
  5. [转]在Ubuntu 下安装Redis 并使用init 脚本启动
  6. Redis Key 命令
  7. tinyxml2简单使用
  8. Gulp那些好用的插件 2016.04.20
  9. [LeetCode#202] Roman to Integer
  10. 使用PDO连接数据库 查询和插入乱码的解决方法
  11. 各种类型Android源代码
  12. springMVC 静态文件 访问
  13. 大数据:Parquet文件存储格式
  14. mysql 按出现次数排序
  15. sqlserver2017 重装过程中出现“无法找到数据库引擎启动句柄”错误的解决办法
  16. iOS-CoreLocation地理编码(转载)
  17. 容器list使用之erase(其他容器也通用)
  18. Python urlparse模块
  19. 切线空间(Tangent Space)法线映射(Normal Mapping)【转】
  20. 第三篇:Spark SQL Catalyst源码分析之Analyzer

热门文章

  1. 修改MAC系统下默认PHP版本(解决自带版本和环境版本冲突)
  2. P7294-[USACO21JAN]Minimum Cost Paths P【单调栈】
  3. react之四种组件中DOM样式设置方式
  4. 20 行代码:Serverless 架构下用 Python 轻松搞定图像分类和预测
  5. 通过Swagger文档生成前端service文件,提升前端开发效率
  6. CQOI2021 退役记
  7. 简单几步零成本使用Vercel部署OneIndex 无需服务器搭建基于OneDrive的网盘
  8. 【集成学习】:Stacking原理以及Python代码实现
  9. Spring框架访问数据库的两种方式的小案例
  10. Java(35)IO特殊操作流&amp;Properties集合