springboot+mybatis上传图片保存到数据库,以及读取并在页面显示
1、mapper.xml文件
<insert id="insertOne" parameterType="java.util.Map"> insert into imgtest (img) values (#{img, jdbcType=BLOB}) </insert>
2、pojo里,类型为byte[]
3、controller
存数据库
@RequestMapping(value = "/addImg", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> addImg(HttpServletRequest request,
@RequestParam("file") MultipartFile file){
Map<String, Object> result = new HashMap<>();
Map<String ,Object> params = new HashMap<>();
try {
byte[] data;
data = file.getBytes();
params.put("img", data);
//插入数据库
}catch (Exception e){
e.printStackTrace();
}
result.put("message", "上传成功");
return result;
}
读取
@RequestMapping(value = "/getImgById", method = RequestMethod.GET)
public void getImgById(@RequestParam(value = "id")Long id,
HttpServletResponse response){
try {
ImgTest imgTest = imgService.getImgById(id);
byte[] data = imgTest.getImg();
response.setContentType("image/jpeg");
response.setCharacterEncoding("UTF-8");
OutputStream outputSream = response.getOutputStream();
outputSream.write(data);
outputSream.flush();
}catch (IOException e){
e.printStackTrace();
}
}
4、页面:
<form action="/addImg" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
<br>
<img src = "/getImgById?id=1">
版权声明:本文为anjingjingg原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。