1.搭建环境:JDK1.8+IDEA2017+MySQL8.0
2.功能需求:插入图片
3.数据库表:
DROP TABLE IF EXISTS `ebiz_img`;
CREATE TABLE `ebiz_img` (
`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '图片保存表',
`img_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片名称',
`img_base64` longtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'base64',
`product_id` int(0) NULL DEFAULT NULL COMMENT '产品id',
`user_id` int(0) NULL DEFAULT NULL COMMENT '用户id',
`img_location` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '存储路径D:\\example\\',
`domain` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'url:http://www.example.com/',
`type` int(0) NULL DEFAULT NULL COMMENT '1-头像;2-产品列表页;3-产品详情页;4-首页轮播图',
`is_delete` int(0) NULL DEFAULT 0,
`created_date` datetime(0) NULL DEFAULT NULL,
`modified_date` datetime(0) NULL DEFAULT NULL,
`created_user` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`modified_user` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
4.model类
package com.example.shop.model;
import java.util.Date;
public class EbizImg {
private Integer id;
private String imgName;
private String imgBase64;
private Integer productId;
private Integer userId;
private String imgLocation;
private String domain;
private Integer type;
private Integer isDelete;
private Date createdDate;
private Date modifiedDate;
private String createdUser;
private String modifiedUser;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String getImgBase64() {
return imgBase64;
}
public void setImgBase64(String imgBase64) {
this.imgBase64 = imgBase64;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getImgLocation() {
return imgLocation;
}
public void setImgLocation(String imgLocation) {
this.imgLocation = imgLocation;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getCreatedUser() {
return createdUser;
}
public void setCreatedUser(String createdUser) {
this.createdUser = createdUser;
}
public String getModifiedUser() {
return modifiedUser;
}
public void setModifiedUser(String modifiedUser) {
this.modifiedUser = modifiedUser;
}
}
5.自动生成mybatis代码
<table tableName="ebiz_img" domainObjectName="EbizImg" mapperName="EbizImgDAO" >
<generatedKey column="id" sqlStatement="Mysql" identity="true"/>
</table>
6.编写自定义的DTO类
package com.example.shop.dto;
import lombok.Data;
import java.util.Date;
@Data
public class EbizImgDTO {
private Integer id;
/**
* 图片名
*/
private String imgName;
/**
* Base64
*/
private String imgBase64;
/**
* 产品id
*/
private Integer productId;
/**
* 用户id
*/
private Integer userId;
/**
* 物理盘符位置
*/
private String imgLocation;
/**
* url
*/
private String domain;
/**
* 类型
*/
private Integer type;
private Date createdDate;
private Date modifiedDate;
private String createdUser;
private String modifiedUser;
}
7.编写ImgSpecDAO.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.example.shop.dao.EbizImgSpecDAO">
<insert id="insertImg" parameterType="com.example.shop.dto.EbizImgDTO" useGeneratedKeys="true" keyProperty="id">
insert into ebiz_img (
img_base64,
domain,
product_id,
user_id,
type,
img_location,
img_name,
created_user,
created_date,
is_delete
)values(
#{imgBase64},
#{domain},
#{productId},
#{userId},
#{type},
#{imgLocation},
#{imgName},
#{createdUser},
#{createdDate},
0
)
</insert>
</mapper>
8.编写EbizImgSpecDAO接口
package com.example.shop.dao;
import com.example.shop.dto.EbizImgDTO;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
/**
* @author EBIZ
*/
@Component
@Mapper
public interface EbizImgSpecDAO {
int insertImg (EbizImgDTO ebizImgDTO);
}
9.编写EbizImgService接口
package com.example.shop.service;
import com.example.shop.dto.EbizImgDTO;
public interface EbizImgService {
int insertImg(EbizImgDTO imgDTO,String username);
}
10.编写实现类
package com.example.shop.service.impl;
import com.example.shop.dao.EbizImgSpecDAO;
import com.example.shop.dto.EbizImgDTO;
import com.example.shop.service.EbizImgService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
/**
* @author EBIZ
*/
@Service
public class EbizImgServiceImpl implements EbizImgService {
@Autowired
EbizImgSpecDAO imgSpecDAO;
@Override
public int insertImg(EbizImgDTO imgDTO, String username) {
Base64.Decoder decoder = Base64.getDecoder();
//切掉,以前的请求头部分 取出base64部分
//substring() 方法返回字符串的子字符串 indexOf返回某个指定的字符串值在字符串中首次出现的位置
String base64 = imgDTO.getImgBase64().substring(imgDTO.getImgBase64().indexOf(",") + 1);
//通用唯一识别码 randomUUID自动生成主键的方法
UUID uuid = UUID.randomUUID();
//获取format “data:image/png;base64,”截取/与;中间部分
String format = imgDTO.getImgBase64().substring(imgDTO.getImgBase64().indexOf("/") + 1, imgDTO.getImgBase64().indexOf(";"));
//图片名称
String imgName = uuid + "." + format;
//存盘位置
String location = "D:/shop/img";
Date date = new Date();
//图片url
String domain = new SimpleDateFormat("/yyyy/MM_dd/").format(date) + imgName;
//定义path 位置:url
String path = location + domain;
try {
// Base64解码
byte[] bytes = decoder.decode(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
Boolean b = !StringUtils.contains("jpg", format) && (!StringUtils.contains("png", format) && (!StringUtils.contains("bmp", format) && (StringUtils.contains("", format))));
//如果解码后包含这几种格式的字符串 则-1 否则进行生成
if (b) {
return -1;
}
// 生成jpg图片
File file = new File(path);
File fileParent = file.getParentFile();
//如果父目录不存在 则创建 否则继续生成
if (!fileParent.exists()) {
file.getParentFile().mkdirs();
}
//在path路径下输出文件
OutputStream out = new FileOutputStream(path);
out.write(bytes);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
imgDTO.setImgBase64(base64);
imgDTO.setImgName(imgName);
imgDTO.setDomain(domain);
imgDTO.setImgLocation(path);
return imgSpecDAO.insertImg(imgDTO);
}
}
11.编写控制类
package com.example.shop.controller;
import com.example.shop.common.util.ResultModel;
import com.example.shop.dto.EbizImgDTO;
import com.example.shop.service.EbizImgService;
import com.example.shop.service.impl.EbizImgServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* @author EBIZ
*/
@Controller
@RequestMapping("/img")
public class EbizPictureController {
@Autowired
EbizImgService imgService;
@PostMapping("/insert")
@ResponseBody //post方法
public ResultModel insertAllInformation(@RequestBody EbizImgDTO imgDTO, HttpServletRequest request) {
//从session中获取用户名
String username = (String) request.getSession().getAttribute("username");
//入参校验
String base64 = imgDTO.getImgBase64();
//如果base64长度不为0则进行下一步判断
if (base64.length() == 0) {
return ResultModel.error("base64为空");
}
//如果图片类型不为空则进行下一步判断
if (imgDTO.getType() == null) {
return ResultModel.error("图片类型为空");
}
//商品id 或 用户id 不为空 则进行添加
if (imgDTO.getProductId() == null && imgDTO.getUserId() == null) {
return ResultModel.error("用户id和商品i不能都为空");
}
//添加图片
int count = imgService.insertImg(imgDTO, username);
if (count == -1) {
return ResultModel.error("添加失败,请注意格式");
}
return ResultModel.success("添加成功");
}
}