天天看點

postgre存儲bytea類型(blob)

postgre存儲bytea類型(blob)

1.conrtoller

public Result<SysImageVO> uploadImg(SysImageVO sysImageVO, MultipartFile imgFile) throws IOException {
        Result<SysImageVO> result = new Result<>();
        sysImageVO.setContent(imgFile.getBytes());
        sysImageService.uploadImg(sysImageVO);
        return result;
    }
 
 
    public Result downloadImg(SysImageVO sysImageVO, HttpServletResponse response) throws IOException {
        Result result = new Result();
        // 業務處理
        SysImageVO image = sysImageService.downloadImg(sysImageVO);
        // 将content轉化
        byte[] content = (byte[]) image.getContent();
        // 設定檔案名
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(image.getName(), "UTF-8") + ";");
        // 設定檔案大小
        response.setContentLength(Integer.parseInt(image.getSize()));
        // 将圖檔流通過response對象傳回
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        bos.write(content);
        bos.close();
        return result;
    }      

2.entity

private Object content; //二進制流      

3.mapper

<?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.vanpeng.resource.business.modular.image.dao.SysImageDao">
        <resultMap type="xx.entity.ImageVO" id="ImageMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="content" column="content" jdbcType="BLOB"/> //bytea
    </resultMap>
 
    <!--新增圖檔-->
    <insert id="uploadImg">
        insert into sys_image(id, name, content)
        values (#{id, jdbcType=INTEGER},#{name, jdbcType=VARCHAR}, #{content})
    </insert>
 
    <!--下載下傳圖檔-->
    <select id="getImgById" resultMap="ImageMap">
        select
        id, name, content
        from sys_image
        where id = #{id}
    </select>
</mapper>      

4.service

service不多說,對象傳遞即可。