上传
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">

本文详细介绍了使用MultipartFile进行文件上传的实现方法,包括将文件转换为字节数组存储到数据库,以及从数据库中读取文件并提供下载功能的过程。同时,展示了如何通过前端展示已上传的图片。
548

被折叠的 条评论
为什么被折叠?



