器材管理
和员工管理基本一致,就不赘述,展示代码为主
新增器材
表设计:
|-------------|--------------|---------|---------|
| 字段名 | 数据类型 | 说明 | 备注 |
| id | bigint | 主键 | 自增 |
| name | varchar(32) | 器材名字 | |
| img | varchar(255) | 图片 | |
| number | BIGINT | 器材数量 | |
| comment | VARCHAR(99) | 器材描述 | |
| status | Int | 器材状态 | 1正常 0锁定 |
| create_time | Datetime | 创建时间 | |
| update_time | datetime | 最后修改时间 | 借走/归还 |
| create_user | bigint | 创建人id | |
| update_user | bigint | 最后修改人id | 借走或者归还 |
sql语句
CREATE TABLE equipment (
id BIGINT AUTO_INCREMENT PRIMARY KEY, -- 自增主键
name VARCHAR(32) NOT NULL, -- 器材名字,不允许为空
number BIGINT NOT NULL default 1, -- 器材数量:默认为1
comment VARCHAR(99) , -- 器材描述
status INT NOT NULL DEFAULT 1, -- 器材状态,默认为1(正常),0表示锁定
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, -- 创建时间,默认为当前时间
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- 最后修改时间,默认为当前时间,并在每次更新时自动更新
create_user BIGINT NOT NULL, -- 创建人id,不允许为空
update_user BIGINT NOT NULL, -- 最后修改人id,不允许为空
FOREIGN KEY (create_user) REFERENCES student(id),
FOREIGN KEY (update_user) REFERENCES student(id)
-- 注意:这里假设create_user和update_user是用户ID,您需要确保这些ID在相应的用户表中存在
);
INSERT INTO equipment VALUES (1,'篮球',10,'这是篮球',1,'2024-07-12','2024-07-12',1,1);
ALTER TABLE equipment ADD COLUMN img VARCHAR(255);
接口设计
请求路径:/admin/equipment
请求方式:POST
请求参数:Headers:"Content-Type": "application/json"
请求体:Body:
id;name,img, number,comment;
返回数据:code;data;msg
代码开发
实体类
创建数据库的器材的封装实体类
sems-pojo/src/main/java/com/ljc/entity/Equipment.java
package com.ljc.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.security.SecureRandom;
import java.time.LocalDateTime;
@Data
@Builder //可是使用builder方式来定义数据
@NoArgsConstructor //无参构造器
@AllArgsConstructor //有参构造器
public class Equipment implements Serializable {
private static final long serialVersionUID = 1L;//告诉Java虚拟机(JVM)这个类的对象是可以被序列化的。
private Long id;
private String name;
//图片
private String img;
//器材数量
private Long number;
//器材描述
private String comment;
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
private Long createUser;
private Long updateUser;
}
接收前端的数据,创建实体类DTO
sems-pojo/src/main/java/com/ljc/dto/EquipmentDTO.java
package com.ljc.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public class EquipmentDTO implements Serializable {
//器材id
private Long id;
//器材名字
private String name;
//图片
private String img;
//器材数量
private Long number;
//器材描述
private String comment;
}
controller
sems-server/src/main/java/com/ljc/controller/admin/EquipmentController.java
package com.ljc.controller.admin;
import com.ljc.dto.EquipmentDTO;
import com.ljc.result.Result;
import com.ljc.service.EquipmentService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.RestController;
@RestController
@RequestMapping("/admin/equipment")
@Slf4j
public class EquipmentController {
@Autowired
private EquipmentService equipmentService;
/**
* 新增器材
* @param equipmentDTO
* @return
*/
@PostMapping
@ApiOperation("新增器材")
public Result save(EquipmentDTO equipmentDTO){
log.info("新增器材:{}", equipmentDTO);
equipmentService.save(equipmentDTO);
return Result.success();
}
}
service
sems-server/src/main/java/com/ljc/service/EquipmentService.java
package com.ljc.service;
import com.ljc.dto.EquipmentDTO;
public interface EquipmentService {
/**
* 新增器材
* @param equipmentDTO
*/
void save(EquipmentDTO equipmentDTO);
}
serviceImpl
sems-server/src/main/java/com/ljc/service/impl/EquipmentServiceImpl.java
package com.ljc.service.impl;
import com.ljc.constant.StatusConstant;
import com.ljc.context.BaseContext;
import com.ljc.dto.EquipmentDTO;
import com.ljc.entity.Equipment;
import com.ljc.mapper.EquipmentMapper;
import com.ljc.service.EquipmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@Service
public class EquipmentServiceImpl implements EquipmentService {
@Autowired
private EquipmentMapper equipmentMapper;
/**
* 新增器材
* @param equipmentDTO
*/
@Override
public void save(EquipmentDTO equipmentDTO) {
//1. 先创建一个器材实体类
Equipment equipment = new Equipment();
//2. 将DTO数据copy到实体类去
BeanUtils.copyProperties(equipmentDTO,equipment);
//2.1 补充其余数据
//状态:默认为1;
equipment.setStatus(StatusConstant.ENABLE);
//修改时间
equipment.setCreateTime(LocalDateTime.now());
equipment.setUpdateTime(LocalDateTime.now());
//创建/修改人id
equipment.setCreateUser(BaseContext.getCurrentId());
equipment.setUpdateUser(BaseContext.getCurrentId());
//3. 调用mapper层查询数据库
equipmentMapper.insert(equipment);
}
}
mapper
sems-server/src/main/java/com/ljc/mapper/EquipmentMapper.java
package com.ljc.mapper;
import com.ljc.entity.Equipment;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface EquipmentMapper {
/**
* 新增器材
* @param equipment
*/
@Insert("insert into equipment (name, img,status,number,comment, create_time, update_time, create_user, update_user)" +
"VALUES " +
"(#{name},#{img},#{status},#{number},#{comment},#{createTime},#{updateTime},#{createUser},#{updateUser})")
void insert(Equipment equipment);
}
测试
//图片后面解决,使用OSS云存储
器材分页查询
接口设计
请求路径:/admin/equipment/page
请求方式:GET
请求参数: name, page, pageSize;
返回数据:code;msg ;data:total,records;
controller层
sems-server/src/main/java/com/ljc/controller/admin/EquipmentController.java
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
@GetMapping("/page")
@ApiOperation("器材分页查询")
public Result<PageResult> page(EquipmentPageQueryDTO equipmentPageQueryDTO){
log.info("器材分页查询:{}",equipmentPageQueryDTO);
PageResult pageResult = equipmentService.page(equipmentPageQueryDTO);
return Result.success(pageResult);
}
service层
sems-server/src/main/java/com/ljc/service/EquipmentService.java
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
PageResult page(EquipmentPageQueryDTO equipmentPageQueryDTO);
serviceImpl层
sems-server/src/main/java/com/ljc/service/impl/EquipmentServiceImpl.java
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
@Override
public PageResult page(EquipmentPageQueryDTO equipmentPageQueryDTO) {
PageHelper.startPage(equipmentPageQueryDTO.getPage(),equipmentPageQueryDTO.getPageSize());
Page<Equipment> page = equipmentMapper.page(equipmentPageQueryDTO);
long total = page.getTotal();
List<Equipment> records = page.getResult();
return new PageResult(total,records);
}
mapper层
sems-server/src/main/java/com/ljc/mapper/EquipmentMapper.java
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
Page<Equipment> page(EquipmentPageQueryDTO equipmentPageQueryDTO);
sems-server/src/main/resources/mapper/EquipmentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ljc.mapper.EquipmentMapper">
<!--器材分页查询-->
<select id="page" resultType="com.ljc.entity.Equipment">
select * from equipment
<where>
<if test="name != null and name != ''">
and name like concat('%',#{name},'%')
</if>
</where>
order by create_time desc
</select>
</mapper>
测试
禁用启用器材
接口设计
请求路径:/admin/equipment/status/{status}
请求方式:POST
请求参数:application/json
路径参数:status
query:id
返回数据:code;data;msg
代码设计
controller
sems-server/src/main/java/com/ljc/controller/admin/EquipmentController.java
/**
* 禁用启用器材
* @param status
* @param id
* @return
*/
@PostMapping("/status/{status}")
@ApiOperation("禁用启用器材")
public Result startOrStopEquipmentStatus(@PathVariable Integer status,Long id){
log.info("禁用启用器材...");
equipmentService.startOrStopStatus(status,id);
return Result.success();
}
service和impl层
sems-server/src/main/java/com/ljc/service/EquipmentService.java
/**
* 禁用启用器材
* @param status
* @param id
*/
void startOrStopStatus(Integer status, Long id);
sems-server/src/main/java/com/ljc/service/impl/EquipmentServiceImpl.java
/**
* 禁用启用器材
* @param status
* @param id
*/
@Override
public void startOrStopStatus(Integer status, Long id) {
Equipment equipment = Equipment
.builder()
.id(id)
.status(status)
.build();
equipmentMapper.update(equipment);
}
mapper层
sems-server/src/main/java/com/ljc/mapper/EquipmentMapper.java
/**
* 修改器材表
* @param equipment
*/
void update(Equipment equipment);
sems-server/src/main/resources/mapper/EquipmentMapper.xml
<!--修改-->
<update id="update">
update equipment
<set>
<if test="name != null">name = #{name},</if>
<if test="img != null">img = #{img},</if>
<if test="number != null">number = #{number},</if>
<if test="comment != null">comment = #{comment},</if>
<if test="status != null">status = #{status},</if>
<if test="updateTime != null">update_Time = #{updateTime},</if>
<if test="updateUser != null">update_User = #{updateUser},</if>
</set>
where id = #{id}
</update>
测试
编辑器材信息
接口设计
根据id查询学生
请求路径:/admin/equipment/{id}
请求方法:GET
请求参数:id
返回数据:code;msg;data(equipment类)
编辑学生信息
请求路径:/admin/equipment
请求方法:PUT
请求参数:Headers:application/json
Body:id,name,img,number,comment,status
返回数据:code;msg;data
代码开发
controller
sems-server/src/main/java/com/ljc/controller/admin/EquipmentController.java
/**
* 根据id查询器材信息
* @param id
* @return
*/
@GetMapping("{id}")
@ApiOperation("根据id查询器材信息")
public Result<Equipment> getById(@PathVariable Integer id){
log.info("根据id查询器材信息....");
Equipment equipment = equipmentService.getById(id);
return Result.success(equipment);
}
/**
* 修改器材信息
* @param equipmentDTO
* @return
*/
@PutMapping
@ApiOperation("修改器材信息")
public Result updateEquipmentInfo(@RequestBody EquipmentDTO equipmentDTO){
log.info("修改器材信息...");
equipmentService.updateEquipmentInfo(equipmentDTO);
return Result.success();
}
service
sems-server/src/main/java/com/ljc/service/EquipmentService.java
/**
* 根据id查询信息
* @param id
* @return
*/
Equipment getById(Integer id);
/**
* 修改器材信息
* @param equipmentDTO
*/
void updateEquipmentInfo(EquipmentDTO equipmentDTO);
sems-server/src/main/java/com/ljc/service/impl/EquipmentServiceImpl.java
/**
* 根据id查询信息
* @param id
* @return
*/
@Override
public Equipment getById(Integer id) {
return equipmentMapper.getById(id);
}
/**
* 修改器材信息
* @param equipmentDTO
*/
@Override
public void updateEquipmentInfo(EquipmentDTO equipmentDTO) {
Equipment equipment = new Equipment();
BeanUtils.copyProperties(equipmentDTO,equipment);
equipment.setUpdateUser(BaseContext.getCurrentId());
equipment.setUpdateTime(LocalDateTime.now());
equipmentMapper.update(equipment);
}
mapper
sems-server/src/main/java/com/ljc/mapper/EquipmentMapper.java
/**
* 根据id查找员工信息
* @param id
* @return
*/
@Select("select * from equipment where id = #{id}")
Equipment getById(Integer id);
/**
* 修改器材表
* @param equipment
*/
void update(Equipment equipment);
测试
完整代码
controller
sems-server/src/main/java/com/ljc/controller/admin/EquipmentController.java
package com.ljc.controller.admin;
import com.ljc.dto.EquipmentDTO;
import com.ljc.dto.EquipmentPageQueryDTO;
import com.ljc.entity.Equipment;
import com.ljc.result.PageResult;
import com.ljc.result.Result;
import com.ljc.service.EquipmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/admin/equipment")
@Slf4j
@Api(tags = "器材管理")
public class EquipmentController {
@Autowired
private EquipmentService equipmentService;
/**
* 新增器材
* @param equipmentDTO
* @return
*/
@PostMapping
@ApiOperation("新增器材")
public Result save(@RequestBody EquipmentDTO equipmentDTO){
log.info("新增器材:{}", equipmentDTO);
equipmentService.save(equipmentDTO);
return Result.success();
}
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
@GetMapping("/page")
@ApiOperation("器材分页查询")
public Result<PageResult> page(EquipmentPageQueryDTO equipmentPageQueryDTO){
log.info("器材分页查询:{}",equipmentPageQueryDTO);
PageResult pageResult = equipmentService.page(equipmentPageQueryDTO);
return Result.success(pageResult);
}
/**
* 禁用启用器材
* @param status
* @param id
* @return
*/
@PostMapping("/status/{status}")
@ApiOperation("禁用启用器材")
public Result startOrStopEquipmentStatus(@PathVariable Integer status,Long id){
log.info("禁用启用器材...");
equipmentService.startOrStopStatus(status,id);
return Result.success();
}
/**
* 根据id查询器材信息
* @param id
* @return
*/
@GetMapping("{id}")
@ApiOperation("根据id查询器材信息")
public Result<Equipment> getById(@PathVariable Integer id){
log.info("根据id查询器材信息....");
Equipment equipment = equipmentService.getById(id);
return Result.success(equipment);
}
/**
* 修改器材信息
* @param equipmentDTO
* @return
*/
@PutMapping
@ApiOperation("修改器材信息")
public Result updateEquipmentInfo(@RequestBody EquipmentDTO equipmentDTO){
log.info("修改器材信息...");
equipmentService.updateEquipmentInfo(equipmentDTO);
return Result.success();
}
}
service
sems-server/src/main/java/com/ljc/service/EquipmentService.java
package com.ljc.service;
import com.ljc.dto.EquipmentDTO;
import com.ljc.dto.EquipmentPageQueryDTO;
import com.ljc.entity.Equipment;
import com.ljc.result.PageResult;
public interface EquipmentService {
/**
* 新增器材
* @param equipmentDTO
*/
void save(EquipmentDTO equipmentDTO);
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
PageResult page(EquipmentPageQueryDTO equipmentPageQueryDTO);
/**
* 禁用启用器材
* @param status
* @param id
*/
void startOrStopStatus(Integer status, Long id);
/**
* 根据id查询信息
* @param id
* @return
*/
Equipment getById(Integer id);
/**
* 修改器材信息
* @param equipmentDTO
*/
void updateEquipmentInfo(EquipmentDTO equipmentDTO);
}
sems-server/src/main/java/com/ljc/service/impl/EquipmentServiceImpl.java
package com.ljc.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ljc.constant.StatusConstant;
import com.ljc.context.BaseContext;
import com.ljc.dto.EquipmentDTO;
import com.ljc.dto.EquipmentPageQueryDTO;
import com.ljc.entity.Equipment;
import com.ljc.mapper.EquipmentMapper;
import com.ljc.result.PageResult;
import com.ljc.service.EquipmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class EquipmentServiceImpl implements EquipmentService {
@Autowired
private EquipmentMapper equipmentMapper;
/**
* 新增器材
* @param equipmentDTO
*/
@Override
public void save(EquipmentDTO equipmentDTO) {
//1. 先创建一个器材实体类
Equipment equipment = new Equipment();
//2. 将DTO数据copy到实体类去
BeanUtils.copyProperties(equipmentDTO,equipment);
//2.1 补充其余数据
//状态:默认为1;
equipment.setStatus(StatusConstant.ENABLE);
//修改时间
equipment.setCreateTime(LocalDateTime.now());
equipment.setUpdateTime(LocalDateTime.now());
//创建/修改人id
equipment.setCreateUser(BaseContext.getCurrentId());
equipment.setUpdateUser(BaseContext.getCurrentId());
//3. 调用mapper层查询数据库
equipmentMapper.insert(equipment);
}
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
@Override
public PageResult page(EquipmentPageQueryDTO equipmentPageQueryDTO) {
PageHelper.startPage(equipmentPageQueryDTO.getPage(),equipmentPageQueryDTO.getPageSize());
Page<Equipment> page = equipmentMapper.page(equipmentPageQueryDTO);
long total = page.getTotal();
List<Equipment> records = page.getResult();
return new PageResult(total,records);
}
/**
* 禁用启用器材
* @param status
* @param id
*/
@Override
public void startOrStopStatus(Integer status, Long id) {
Equipment equipment = Equipment
.builder()
.id(id)
.status(status)
.build();
equipmentMapper.update(equipment);
}
/**
* 根据id查询信息
* @param id
* @return
*/
@Override
public Equipment getById(Integer id) {
return equipmentMapper.getById(id);
}
/**
* 修改器材信息
* @param equipmentDTO
*/
@Override
public void updateEquipmentInfo(EquipmentDTO equipmentDTO) {
Equipment equipment = new Equipment();
BeanUtils.copyProperties(equipmentDTO,equipment);
equipment.setUpdateUser(BaseContext.getCurrentId());
equipment.setUpdateTime(LocalDateTime.now());
equipmentMapper.update(equipment);
}
}
mapper
sems-server/src/main/java/com/ljc/mapper/EquipmentMapper.java
package com.ljc.mapper;
import com.github.pagehelper.Page;
import com.ljc.dto.EquipmentPageQueryDTO;
import com.ljc.entity.Equipment;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface EquipmentMapper {
/**
* 新增器材
* @param equipment
*/
@Insert("insert into equipment (name, img,status,number,comment, create_time, update_time, create_user, update_user)" +
"VALUES " +
"(#{name},#{img},#{status},#{number},#{comment},#{createTime},#{updateTime},#{createUser},#{updateUser})")
void insert(Equipment equipment);
/**
* 器材分页查询
* @param equipmentPageQueryDTO
* @return
*/
Page<Equipment> page(EquipmentPageQueryDTO equipmentPageQueryDTO);
/**
* 根据id查找员工信息
* @param id
* @return
*/
@Select("select * from equipment where id = #{id}")
Equipment getById(Integer id);
/**
* 修改器材表
* @param equipment
*/
void update(Equipment equipment);
}
sems-server/src/main/resources/mapper/EquipmentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ljc.mapper.EquipmentMapper">
<!--修改-->
<update id="update">
update equipment
<set>
<if test="name != null">name = #{name},</if>
<if test="img != null">img = #{img},</if>
<if test="number != null">number = #{number},</if>
<if test="comment != null">comment = #{comment},</if>
<if test="status != null">status = #{status},</if>
<if test="updateTime != null">update_Time = #{updateTime},</if>
<if test="updateUser != null">update_User = #{updateUser},</if>
</set>
where id = #{id}
</update>
<!--器材分页查询-->
<select id="page" resultType="com.ljc.entity.Equipment">
select * from equipment
<where>
<if test="name != null and name != ''">
and name like concat('%',#{name},'%')
</if>
</where>
order by create_time desc
</select>
</mapper>
OSS云上传图片
实现步骤:
1). 定义OSS相关配置
sems-server/src/main/resources/application.yml
server:
port: 8080
spring:
profiles:
active: dev
main:
allow-circular-references: true
datasource:
druid:
driver-class-name: ${ljc.datasource.driver-class-name}
url: jdbc:mysql://${ljc.datasource.host}:${ljc.datasource.port}/${ljc.datasource.database}?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: ${ljc.datasource.username}
password: ${ljc.datasource.password}
mybatis:
#mapper配置文件
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.ljc.entity
configuration:
#开启驼峰命名
map-underscore-to-camel-case: true
logging:
level:
com:
sky:
mapper: debug
service: info
controller: info
ljc:
jwt:
# 设置jwt签名加密时使用的秘钥
admin-secret-key: kussm
# 设置jwt过期时间
admin-ttl: 7200000
# 设置前端传递过来的令牌名称
admin-token-name: token
alioss:
bucket-name: ${ljc.alioss.bucket-name}
access-key-secret: ${ljc.alioss.access-key-secret}
access-key-id: ${ljc.alioss.access-key-id}
endpoint: ${ljc.alioss.endpoint}
sems-server/src/main/resources/application-dev.yml
ljc:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
host: localhost
port: 3306
database: sems
username: root
password: 8888
alioss:
endpoint: oss-cn-hangzhou.aliyuncs.com
access-key-id: LTAI5tBt5pkXempSC5vPAocu
access-key-secret: XDMFmdEjA6c8Tl5a4xCg4dF4avoJtM
bucket-name: kussmcx
2). 读取OSS配置
sems-common/src/main/java/com/ljc/properties/AliOssProperties.java
package com.ljc.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "ljc.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
3). 生成OSS工具类对象
sems-server/src/main/java/com/ljc/config/OssConfiguration.java
package com.ljc.config;
import com.ljc.properties.AliOssProperties;
import com.ljc.utils.AliOssUtil;
import com.ljc.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration//配置类特有的注释
@Slf4j
public class OssConfiguration {
@Bean
@ConditionalOnMissingBean
public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
return new AliOssUtil(aliOssProperties.getEndpoint(),
aliOssProperties.getAccessKeyId(),
aliOssProperties.getAccessKeySecret(),
aliOssProperties.getBucketName());
}
}
其中sems-common/src/main/java/com/ljc/utils/AliOssUtil.java
package com.ljc.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上传到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}
4). 定义文件上传接口
在sems-server/src/main/java/com/ljc/controller/admin/CommonController.java
package com.ljc.controller.admin;
import com.ljc.utils.AliOssUtil;
import com.ljc.constant.MessageConstant;
import com.ljc.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
/**
* 通用接口,上传文件(图片)
*/
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {
@Autowired
private AliOssUtil aliOssUtil;
@ApiOperation("文件上传")
@PostMapping("/upload")
public Result<String> upload(MultipartFile file){
log.info("文件上传:{}" + file);
try {
//objectname使用UUID来生成
//1.获取原始文件名称
String originalFilename = file.getOriginalFilename();
//2.截取文件的后缀
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//获取文件.之后的部分
//3.构建新文件名称
String newFilename = UUID.randomUUID().toString() + suffix;
String filePash = aliOssUtil.upload(file.getBytes(), newFilename);//调用upload的方法
return Result.success(filePash);//调用aliossUtil修改后的数据,这样才能将访问路劲改为oss云的;
} catch (IOException e) {
log.info(MessageConstant.UPLOAD_FAILED + e);
}
return Result.error(MessageConstant.UPLOAD_FAILED);//文件上传失败的常量;
}
}