圖片在數據表中以blob類型字段的存儲
前端界面,form表單提交,需要注意的點是 enctype ="multipart/form-data ,multipart/form-data是指表單數據有多部分構成,既有文本數據,又有文件等二進制數據的意思。
需要注意的是:默認情況下,enctype的值是application/x-www-form-urlencoded,不能用於文件上傳,只有使用了multipart/form-data,才能完整的傳遞文件數據。
<form action="/student/saveimg" method="post" enctype ="multipart/form-data"> <label for="file" class="btn btn-primary" style="float: left;height: 30px;width: 180px;margin-right: 20px">選擇考生照片</label> <input id="file" name="file" type="file" style="float: left;display:none"/> <input class="btn btn-primary" type="submit" value="提交" style="float: left"> </form>
后端接收代碼
Controller層
@PostMapping (value = "/saveimg") @ResponseBody public Object searchMember(MultipartFile file){ try { InputStream ins = file.getInputStream(); byte[] buffer=new byte[1024]; int len=0; ByteArrayOutputStream bos=new ByteArrayOutputStream(); while((len=ins.read(buffer))!=-1){ bos.write(buffer,0,len); } bos.flush(); byte data[] = bos.toByteArray(); Student s=new Student(); s.setId(sId); s.setPhoto(data); studentService.insertPhoto(s); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS_TIP; }
service層
Integer insertPhoto(Student s);
service實現層
public Integer insertPhoto(Student s){ return student.insertPhoto(s); }
mapper層
<update id="insertPhoto" parameterType="com.system.model.Student"> update ies_student set photo = #{photo} where id = #{id} </update>
實體類中photo字段用byte[]類型進行存儲,數據表blob類型字段用對象進行存儲,直接傳遞數組時sql接收不到數據信息。
我這里第一遍用此方法時不知道為什么總是報錯sql接收不到數據信息,sql語句錯了???還是其他問題咱也不知道咱也不敢問,好在現在問題是解決了的