一、简介
- 本文章主要实现前端选择图片以MultipartFile形式发送至后端。
- 后端接收文件转化为Blob格式,存储到数据库中。
二、前端实现
- 同步方式代码
<div> <form action="/sendFile" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="text" name="text" /> <input type="submit" /> </form> </div>
- 异步方式代码
<div> <input id="file" type="file" /> <button id="showFile">wjtjcsndmy</button> </div> <script> $("#showFile").on("click",function(){ var file = $("#file")[0].files[0]; console.log(file); var formData = new FormData(); formData.append("file",file); $.ajax({ url : "/sendFile", data : formData, type : "post", processData:false, contentType:false, success: function(res){ console.log(res); }, error:function(){ console.log("Hello Error!"); } }) }) </script>
三、后端实现
-
Controller层
@RequestMapping(value = "/sendFile",method = RequestMethod.POST) public String sendFile(MultipartFile file){ int count = fileService.saveFile(file); if (count == 1){ return "Success"; }else{ return "Error"; } }
-
ServiceImpl实现类
@Override public int saveFile(MultipartFile file) { String id = String.valueOf(UUID.randomUUID()); //生成uuid作为唯一标识 Blob blob = null; try { blob = new SerialBlob(file.getBytes()); //将MultipartFile转 Blob } catch (Exception e) { e.printStackTrace(); } return fileMapper.saveFile(id,blob); }
-
Mapper.xml
<insert id="saveFile"> insert into file(fileid,file) values (#{fileId},#{file}) </insert>
四、查询图片
-
file.html
<div> <img style="width: 200px;" src="getPic?fileId=101" /> </div>
-
Controller
@RequestMapping(value = "/getPic",method = RequestMethod.GET) public void getPic(HttpServletResponse response,String fileId){ ServletOutputStream out = null; List<Map<String, Object>> list = fileService.getFile(fileId); byte[] b = (byte[]) list.get(0).get("file"); InputStream is = new ByteArrayInputStream(b); response.setContentType("image/*"); try { out = response.getOutputStream(); int len = 0; byte[] buf = new byte[1024]; while ((len = is.read(buf,0,1024)) != -1){ out.write(buf,0,len); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
-
Mapper.xml
<select id="getFile" resultType="Map"> select fileid,file from file where fileid = #{fileId} </select>