2021-08-04shopCGoods表的增删改查

shopCGoods表的分页查询,编辑CGoods,批量导出接口,启用接口

1分页查询

2编辑CGoods,上传图片

2.1上传图片需要controller层调用图片管理service层业务方法即可

2.1.0上传图片业务方法

package com.jxmcloud.business.shop.util;

import com.aliyun.oss.OSSClient;

import com.jxmcloud.business.shop.config.ConfigProperties;
import com.jxmcloud.core.utils.helper.FileUtil;
import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
 * 上传文件工具类
 * @author hujun
 **/
@Service
public class SaveFileUtil {
	
	private final Logger logger = LoggerFactory.getLogger(SaveFileUtil.class);
	
	@Autowired
	private ConfigProperties configProperties;


	/**
	 * 图片上传到oss
	 * @author hujun
	 **/
	public String saveFileOSS(MultipartFile file) {
		try {
			if (file.getSize() >= configProperties.getCompressionSize() * 1024)//大于1m就压缩
			{
				//压缩文件
				String fileName = FileUtil.genTempFileName(file.getName());
				int suffixIdx = file.getOriginalFilename().lastIndexOf(".");
				String suffix = file.getOriginalFilename().substring(suffixIdx);
				File tmpFile = File.createTempFile(fileName, suffix);
				FileUtils.copyInputStreamToFile(file.getInputStream(), tmpFile);
				BufferedImage bufferedImage = ImageIO.read(tmpFile);
				if (bufferedImage.getWidth() > configProperties.getScaleSize()) {
					Thumbnails.of(file.getInputStream()).scale(Double.valueOf(configProperties.getScale())).outputQuality(Double.valueOf(configProperties.getOutputQuality())).toFile(tmpFile);
				} else {
					Thumbnails.of(file.getInputStream()).size(bufferedImage.getWidth(), bufferedImage.getHeight()).outputQuality(Double.valueOf(configProperties.getOutputQuality())).toFile(tmpFile);
				}
				return saveImg(new FileInputStream(tmpFile),file.getOriginalFilename());
			} else {
				return saveImg(file.getInputStream(),file.getOriginalFilename());
			}
		} catch (Exception e) {
			logger.error("文件上传失败!", e);
		}
		return null;
	}
	/**
	 * oss上传视频
	 * @author hujun
	 **/
	public String saveFileOSS(InputStream inputStream,String fileName) {
		String bucketName = "zhongwei-info";
		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
		String accessKeyId = "LTAIiljpBscLJmvp";
		String accessKeySecret = "6In1qgERqX15nFi9kXT7n8WoFfdqLi";
		String ossFilePath="uploadFiles/shop/mp4/";
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		fileName=getRadomFileName(fileName);
		ossClient.putObject(bucketName, ossFilePath+fileName, inputStream);
		return "http://jifutongjr.com/"+ossFilePath+fileName;
	}
	/**
	 * oss上传图片
	 * @author hujun
	 **/
	public String saveImg(InputStream inputStream,String fileName) {
		String bucketName="zw-resource";
		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
		String accessKeyId = "LTAIiljpBscLJmvp";
		String accessKeySecret = "6In1qgERqX15nFi9kXT7n8WoFfdqLi";
		String ossFilePath="uploadFiles/shop/img/";
		fileName=getRadomFileName(fileName);
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		ossClient.putObject(bucketName, ossFilePath+fileName, inputStream);
		return "http://zhongwei-info.com/"+ossFilePath+fileName;
	}


	/**
	 * @author charles
	 * @date 2019/4/11 10:59
	 * @desc 删除单个文件
	 */
	public Integer deleteFile(String filePath){
		String bucketName = "zw-resource";
		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
		String accessKeyId = "LTAIiljpBscLJmvp";
		String accessKeySecret = "6In1qgERqX15nFi9kXT7n8WoFfdqLi";
		//http://jifutongjr.com/uploadFiles/award/mp4/2019040714311455396.mp4
		int index = filePath.lastIndexOf("uploadFiles");
		if (index == -1){
			return null;
		}
		String objectName = filePath.substring(index);
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		boolean found = ossClient.doesObjectExist(bucketName, objectName);
		if (found){
			ossClient.deleteObject(bucketName, objectName);
		}
		ossClient.shutdown();
		return 1;
	}

	/**
	 * 获取文件名
	 * @author hujun
	 **/
	private String getRadomFileName(String fileName) {
		String extName = fileName.substring(fileName.lastIndexOf("."));
		String nowTimeStr = ""; // 保存当前时间
		SimpleDateFormat sDateFormat;
		Random r = new Random();
		Date date = new Date();
		// 生成随机文件名:当前年月日时分秒+五位随机数(为了在实际项目中防止文件同名而进行的处理)
		int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; //
		// 获取随机数
		sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // 时间格式化的格式
		nowTimeStr = sDateFormat.format(date); // 当前时间
		return nowTimeStr + rannum + extName;//生成的随机文件名
	}

	/**
	 * @author charles
	 * @date 2019/4/11 14:16
	 * @desc 删除单个文件
	 */
	public String deleteSingleFile(String filePath) {
		if (StringUtils.isBlank(filePath)){
			return "文件路径不能为空!";
		}
		try {
			Integer result = deleteFile(filePath);
			if (result == null){
				return "文件路径不合法!";
			}
			return null;
		} catch (Exception e) {
			logger.error("删除文件失败!", e);
		}
		return "删除失败!";
	}

    /**
     * Excel上传到oss
     * @param file   流文件
     * @param title  文件名
     * @author lipengfei
     **/
    public String saveExcelOSS(MultipartFile file,String title) {
        try {
            String fileName = title+getRadomFileName(".xlsx");
			InputStream inputStream =file.getInputStream();
			String bucketName = "zhongwei-info";
			String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
			String accessKeyId = "LTAIiljpBscLJmvp";
			String accessKeySecret = "6In1qgERqX15nFi9kXT7n8WoFfdqLi";
			String ossFilePath="uploadFiles/shop/excel/";
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			ossClient.putObject(bucketName, ossFilePath+fileName, inputStream);
			return "http://jifutongjr.com/"+ossFilePath+fileName;
        } catch (Exception e) {
            logger.error("Excel文件上传失败!", e);
        }
        return null;
    }

	/**
	 * 保存excel到aliyun oss
	 * @param file
	 * @param title
	 * @return
	 *
	 */
	public String saveMyExcelOSS(MultipartFile file,String title) {
		try {
			InputStream inputStream =file.getInputStream();
			String bucketName = "zhongwei-info";
			String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
			String accessKeyId = "LTAIiljpBscLJmvp";
			String accessKeySecret = "6In1qgERqX15nFi9kXT7n8WoFfdqLi";
			String ossFilePath="uploadFiles/shop/excel/";
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			ossClient.putObject(bucketName, ossFilePath+title, inputStream);
			return "http://jifutongjr.com/"+ossFilePath+title;
		} catch (Exception e) {
			logger.error("Excel文件上传失败!", e);
		}
		return null;
	}


	/**
	 * 上传文件到阿里云
	 * @param fileName
	 * @author lipengfei
	 */
	public String uploadFileOss(String fileName){
		File srcFile = new File(fileName);
		try{
			FileInputStream fileInputStream = new FileInputStream(srcFile);
			MultipartFile multipartFile = new MockMultipartFile(srcFile.getName(), srcFile.getName(),
					ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
			String result = saveFileOSS(multipartFile);
			return result;
		}catch (Exception e){
			logger.error(e.getMessage());
		}
		return null;
	}

	/**
	 * pdf上传到oss
	 * @param file   流文件
	 * @param title  文件名
	 * @author lipengfei
	 **/
	public String savePdfOSS(MultipartFile file,String title) {
		try {
			String fileName = title+".pdf";
			InputStream inputStream =file.getInputStream();
			String bucketName = "zhongwei-info";
			String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
			String accessKeyId = "LTAIiljpBscLJmvp";
			String accessKeySecret = "6In1qgERqX15nFi9kXT7n8WoFfdqLi";
			String ossFilePath="uploadFiles/shop/pdf/";
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			ossClient.putObject(bucketName, ossFilePath+fileName, inputStream);
			return "http://jifutongjr.com/"+ossFilePath+fileName;
		} catch (Exception e) {
			logger.error("PDF文件上传失败!", e);
		}
		return null;
	}
}

//上传图片并不需要自己操作,当图片上传到远程图片服务器之后,我们需要将其查出对其进行校验
@Transactional( rollbackFor = Exception.class)
    public  void saveOrUpdate(GoodsInfoDto goodsInfoDto){
        Goods goods = goodsInfoDto.getGoods();
        List<GoodsImg> goodsImgs= goodsInfoDto.getGoodsImgs();
        if(Objects.isNull(goods.getId())){
            if(Objects.isNull(goods.getBusinessStatus())){
                goods.setBusinessStatus(GoodsStatusEnum.UN_SHELVE.getCode());
            }
            goods.setGoodsNo(serialNumberUtil.generageGoodsNo());
            //查询商品主图,取第一张主图  goods_img 表type 0:商品主图,1:商品图片; img_url是图片路径
            String imgUrl=null;
            if(!PublicUtil.isEmpty(goodsImgs)){
                for(int i=0;i<goodsImgs.size();i++){
                    Integer goodsType = goodsImgs.get(i).getType();
                    if(GoodsImgTypeEnum.MAIN_PICTURE.getCode()==goodsType){
                         imgUrl = goodsImgs.get(i).getImgUrl();
                        break;
                    }
                }
                goods.setGoodsImg(imgUrl);
            }
            ...
            }

GoodsImgService2

package com.jxmcloud.business.shop.service.goods;

import com.jxmcloud.business.shop.mapper.goods.GoodsImgManagementMapper;
import com.jxmcloud.business.shop.model.GoodsImg;
import com.jxmcloud.core.beans.service2.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

/**
 * @author pengzhixiang
 * @createTime 2021-05-13 16:06
 * @desc 上传商品图片Service
 */
@Service
public class GoodsImgService2 extends BaseServiceImpl<GoodsImgManagementMapper, GoodsImg> {

}

GoodsImgManagementMapper

package com.jxmcloud.business.shop.mapper.goods;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jxmcloud.business.shop.model.GoodsImg;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface GoodsImgManagementMapper extends BaseMapper<GoodsImg> {


}

2.1.1商品图片表设计

在这里插入图片描述

2.1.2商品图片实体类

package com.jxmcloud.business.shop.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jxmcloud.core.beans.model.common.BaseEntity;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Table(name = "goods_img")
public class GoodsImg extends BaseEntity {
    @Id
    private Long id;

    /**
     * 商品Id
     */
    @Column(name = "goods_id")
    private Long goodsId;

    /**
     * 图片路径
     */
    @Column(name = "img_url")
    private String imgUrl;

    /**
     * 创建时间
     */
    @Column(name = "create_time")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    /**
     * 小图路径
     */
    @Column(name = "goods_small_img")
    private String goodsSmallImg;

    /**
     * 图片类型
     */
    private Integer type;


    /**
     * 图片说明
     */
    private String  imgValue;

    public String getImgValue() {
        return imgValue;
    }

    public void setImgValue(String imgValue) {
        this.imgValue = imgValue;
    }

    /**
     * @return id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id
     */
    public void setId(Long id) {
        this.id = id;
    }
	/**
     * 获取商户Id
     *
     * @return shop_id - 商户Id
     */
    
    public Long getGoodsId() {
		return goodsId;
	}

    /**
     * 设置商户Id
     *
     * @param shopId 商户Id
     */
	public void setGoodsId(Long goodsId) {
		this.goodsId = goodsId;
	}

    /**
     * 获取图片路径
     *
     * @return img_url - 图片路径
     */
    public String getImgUrl() {
        return imgUrl;
    }

    /**
     * 设置图片路径
     *
     * @param imgUrl 图片路径
     */
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    /**
     * 获取创建时间
     *
     * @return create_time - 创建时间
     */
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * 设置创建时间
     *
     * @param createTime 创建时间
     */
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    /**
     * 获取小图路径
     *
     * @return goodsSmallImg - 小图路径
     */
    public String getGoodsSmallImg() {
		return goodsSmallImg;
	}

    /**
     * 设置小图路径
     *
     * @param goodsSmallImg 小图路径
     */
	public void setGoodsSmallImg(String goodsSmallImg) {
		this.goodsSmallImg = goodsSmallImg;
	}

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }
}

2.1.3GoodsImgMapper

package com.jxmcloud.business.shop.mapper;

import com.jxmcloud.business.shop.model.GoodsImg;
import com.jxmcloud.business.shop.model.ShopImg;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public interface GoodsImgMapper extends Mapper<GoodsImg> {
    List<GoodsImg> getShopImgList(GoodsImg goodsImg);

    /**
     * 通过商品id获取图片
     * @author hujun
     **/
    List<GoodsImg> getImagesByGoodsId(GoodsImg goodsId);

	void delGoodsImg(Long id);

    /**
     * 获取商品图片集合
     * @param goodsId
     * @author chenjingyun
     */
    List<GoodsImg> getGoodsImgs(@Param("goodsId") Long goodsId,@Param("type") Integer type);

    List<GoodsImg> getOneNewGoodsImg(Long goodsId);

    String getGoodsTopImg(Long goodsId);
}

2.1.4GoodsImgService

package com.jxmcloud.business.shop.service;

import com.jxmcloud.business.shop.mapper.GoodsImgMapper;
import com.jxmcloud.business.shop.model.GoodsImg;
import com.jxmcloud.business.shop.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class GoodsImgService {
    @Autowired
    private GoodsImgMapper gsImgMapper;
    @Autowired
    private SysParameterService sysParameterService;

    /**
     * 保存商品主图
     * @author      Mr.Deng
     * @param goodsId,imgstr
     * @date        2018/12/17 14:21
     */
    public void saveGoodsImgs(Long goodsId, String imgstr,Integer type) {
        if(StringUtils.isNotBlank(imgstr)){
            delGoodsImg(goodsId,type);
            String[] arr=imgstr.split(",");
            for (String str : arr) {
                addGoodsImg(goodsId, str,type);
            }
        }else {
            delGoodsImg(goodsId,type);
        }
    }
    /**
     * 删除商品主图
     * @author      Mr.Deng
     * @param goodsId
     * @date        2018/12/17 14:22
     */
    public void delGoodsImg(Long goodsId,Integer type) {
        Example example=new Example(GoodsImg.class);
        example.createCriteria().andEqualTo("goodsId",goodsId).andEqualTo("type",type);
        gsImgMapper.deleteByExample(example);
    }
    /**
     * 添加商品主图
     * @author      Mr.Deng
     * @param goodsId,str
     * @date        2018/12/17 14:24
     */
    public void addGoodsImg(Long goodsId, String str,Integer type) {
        GoodsImg gImg=new GoodsImg();
        gImg.setType(type);
        gImg.setGoodsId(goodsId);
        gImg.setCreateTime(new Date());
        if (!"".equals(str) && str != null) {
            //String picUrl = compressPic.compressPicUrl(str);
            gImg.setImgUrl(str);
            gImg.setGoodsSmallImg(str);
        }
        gsImgMapper.insert(gImg);

    }

    /**
     * 获取商品相关图片
     * @author charles
     */
    public List<GoodsImg> getGoodsImgs(Long id, int type) {
        return gsImgMapper.getGoodsImgs(id,type);
    }

    /**
     * @author charles
     * @date 2019/2/27 15:51
     * @desc 获取商品上传的第一张图片
     */
    public String getGoodsFirstImg(Long goodsId, int type) {
        Example ex = new Example(GoodsImg.class);
        ex.createCriteria().andEqualTo("goodsId",goodsId).andEqualTo("type",type);
        ex.orderBy("id").asc();
        List<GoodsImg> goodsImgs = gsImgMapper.selectByExample(ex);
        if (goodsImgs !=null && goodsImgs.size() > 0){
            return goodsImgs.get(0).getImgUrl();
        }
        return sysParameterService.getValueByKey(Constants.FJSH_PRODUCT_PHOTO);
    }



}

3批量导出数据

4批量启/停用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值