文章目录
- 一、阿里云oss存储服务
- 1、开通 “对象存储OSS”服务
- 2、进入oss管理控制台
- 3、Java代码操作阿里云oss上传文件
- 二、后端集成OSS
- 1、在service模块下创建子模块`service_oss`
- 2、配置pom.xml
- 3、配置application.properties
- 4、主启动类
- 5、启动主启动类,测试项目报错
- 三、实现上传功能
- 1、创建常用类,读取配置文件内容
- 2、文件上传
- 3、控制层
- 4、重启oss服务,Swagger中测试文件上传
- 四、Nginx 反向代理服务器
- 1、安装window版的nginx
- 2、配置nginx实现请求转发的功能
- 五、添加讲师实现头像前端整合
- 1、在添加讲师页面,创建上传组件,实现上传。
- 2、添加讲师页面使用这个复制上传组件
- 3、js脚本实现上传和图片回显
- 4、设置默认头像
- 5、启动测试即可
一、阿里云oss存储服务
为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS。
1、开通 “对象存储OSS”服务
(1)打开阿里云网站 https://www.aliyun.com/
(2)注册阿里云账户,最好使用支付宝,需要实名认证
(3)使用注册的用户登录阿里云里面
(4)找到阿里云oss
(5)开通oss
2、进入oss管理控制台
(1)使用oss,首先创建bucket
创建说明
(2)控制台上传图片
3、Java代码操作阿里云oss上传文件
1、准备工作:创建操作阿里云oss许可证(阿里云颁发id和秘钥)
2、文档位置
快速入门文档:https://help.aliyun.com/document_detail/32011.html?spm=a2c4g.11186623.6.905.23866328891B4P
3、具体使用
(1)创建Maven项目
(2)POM
<dependencies>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
(3)找到编码时需要用到的常量值
- endpoint
- bucketName
- accessKeyId
- accessKeySecret
(4)测试创建Bucket的连接
public class OSSTest {
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.createBucket(bucketName);
ossClient.shutdown();
}
(5)判断存储空间是否存在
@Test
public void testExist() {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
boolean exists = ossClient.doesBucketExist(bucketName);
System.out.println(exists);
ossClient.shutdown();
}
(6)设置存储空间的访问权限
@Test
public void testAccessControl() {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
ossClient.shutdown();
}
二、后端集成OSS
1、在service模块下创建子模块service_oss
2、配置pom.xml
service-oss上级模块service已经引入service的公共依赖,所以service-oss模块只需引入阿里云oss相关依赖即可,
service父模块已经引入了service-base模块,所以Swagger相关默认已经引入
<dependencies>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
3、配置application.properties
#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=guli-file
4、主启动类
@SpringBootApplication
@ComponentScan(basePackages = {"com.kuang"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}
5、启动主启动类,测试项目报错
启动时候,找数据库配置,但是现在模块因为不需要操作数据库,只是做了上传到oss功能,没有配置数据库。
解决方式:
(1)添加上数据库配置
(2)在启动类添加属性,默认不去加载数据库配置【推荐使用】
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
三、实现上传功能
1、创建常用类,读取配置文件内容
@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;
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
2、文件上传
创建Service接口:OssService.java
public interface OssService {
String uploadFileAvator(MultipartFile file);
}
实现:OssServiceImpl.java
参考SDK中的:Java ->上传文件 -> 简单上传 -> 流式上传 -> 上传文件流
package com.kuang.oss.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.kuang.oss.service.OssService;
import com.kuang.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 {
@Override
public String uploadFileAvator(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 {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = file.getInputStream();
String fileName = file.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replaceAll("-","");
fileName = uuid + fileName;
String datePath = new DateTime().toString("yyyy/MM/dd");
fileName = datePath + "/" + fileName;
ossClient.putObject(bucketName, fileName, inputStream);
ossClient.shutdown();
String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
return url;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
3、控制层
创建controller:OssController.java
package com.kuang.oss.controller;
import com.kuang.commonutils.R;
import com.kuang.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@Api(description="阿里云文件管理")
@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {
@Autowired
private OssService ossService;
@ApiOperation(value = "文件上传")
@PostMapping("/upload")
public R uploadOssFile(@ApiParam(name = "file", value = "文件", required = true)
@RequestParam("file") MultipartFile file){
String url = ossService.uploadFileAvator(file);
return R.ok().data("url",url);
}
}
4、重启oss服务,Swagger中测试文件上传
http://localhost:8002/swagger-ui.html
四、Nginx 反向代理服务器
1、安装window版的nginx
下载官网:http://nginx.org/en/download.html
将nginx-1.12.0.zip解压到开发目录中
如:D:\develop\nginx-1.12.2
使用cmd启动nginx ,运行nginx.exe
系统会运行两个nginx进程。
特点:使用cmd启动nginx,如果关闭cmd窗口,nginx不会停止的。
需要使用nginx.exe -s stop
进行手动关闭,重启命令nginx -s reload
2、配置nginx实现请求转发的功能
1、找到nginx配置文件D:\develop\nginx-1.12.2\conf\nginx.conf
2、在nginx.conf进行配置
(1)修改nginx默认端口,把 80 修改 81
(2)配置nginx转发规则
server {
listen 9001;
server_name localhost;
location ~ /eduservice/ {
proxy_pass http://localhost:8001;
}
location ~ /eduuser/ {
proxy_pass http://localhost:8001;
}
location ~ /eduoss/ {
proxy_pass http://localhost:8002;
}
location ~ /eduvod/ {
proxy_pass http://localhost:8003;
}
location ~ /educms/ {
proxy_pass http://localhost:8004;
}
location ~ /ucenterservice/ {
proxy_pass http://localhost:8006;
}
location ~ /edumsm/ {
proxy_pass http://localhost:8005;
}
location ~ /orderservice/ {
proxy_pass http://localhost:8007;
}
location ~ /staservice/ {
proxy_pass http://localhost:8008;
}
location ~ /admin/ {
proxy_pass http://localhost:8009;
}
}
3、修改前端请求地址
(1)修改config/dev.env.js
BASE_API: '"http://localhost:9001"',
(2)重启前端程序
修改配置文件后,需要手动重启前端程序
五、添加讲师实现头像前端整合
1、在添加讲师页面,创建上传组件,实现上传。
使用element-ui组件实现。到源代码里面找到组件,复制到前端项目/src/components
里面
2、添加讲师页面使用这个复制上传组件
src/views/edu/teacher/save.vue
<el-form-item label="讲师头像">
<pan-thumb :image="teacher.avatar"/>
<el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
</el-button>
<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>
引入组件模块
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
3、js脚本实现上传和图片回显
export default {
components: { ImageCropper, PanThumb },
data() {
return {
......,
imagecropperShow:false,
imagecropperKey:0,
BASE_API:process.env.BASE_API,
saveBtnDisabled: false
}
},
methods:{
close() {
this.imagecropperShow = false
this.imagecropperKey = this.imagecropperKey + 1
},
cropSuccess(data) {
this.imagecropperShow=false
this.teacher.avatar=data.url
this.imagecropperKey = this.imagecropperKey + 1
},
......,
}
}
4、设置默认头像
config/dev.env.js中添加阿里云oss bucket地址
OSS_PATH: '"https://guli-file.oss-cn-beijing.aliyuncs.com"'
组件中初始化头像默认地址
const defaultForm = {
......,
avatar: process.env.OSS_PATH + '/avatar/default.jpg'
}
5、启动测试即可
如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发。
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)