上传 public AjaxResult up(MultipartFile file) throws Exception { if (null == file) { return AjaxResult.error("文件为空"); } byte[] imgbytes = file.getBytes(); String filename = file.getOriginalFilename(); logger.info("===filename===" + filename); Attachment attachment = new Attachment(); attachment.setData(imgbytes); attachment.setFilename(filename); yqSelfService.addAttachment(attachment); return AjaxResult.success("成功", attachment.getId()); }
<insert id="addAttachment" useGeneratedKeys="true" keyProperty="id" parameterType="Attachment">
insert into attachment (filename,`data`) values (#{filename},#{data,typeHandler=org.apache.ibatis.type.BlobTypeHandler})
</insert>
文件下载
@GetMapping(value = "/down/file")
public AjaxResult importData(Long id, HttpServletResponse response) throws Exception {
byte[] imgbytes = yqSelfService.findAttachment(id);
if (null != imgbytes) {
OutputStream out = response.getOutputStream();
out.write(imgbytes);
}
return null;
}
public byte[] findAttachment(Long id) {
try {
Map<String, Object> map = yqSelfMapper.findAttachment(id);
return (byte[]) map.get("data");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
<resultMap type="java.util.Map" id="imgResultMap" >
<result property="data" column="data" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>
</resultMap>
<select id="findAttachment" parameterType="map" resultMap="imgResultMap">
SELECT a.`data` FROM attachment a WHERE a.id= #{id}
</select>
前端展示
<img src="https://xxxx.com/v1.0/down/file?id=3">