springboot中图片上传至数据库

图片在数据表中以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语句错了???还是其他问题咱也不知道咱也不敢问,好在现在问题是解决了的

posted @ 2019-05-28 12:54  xiaoWangxiao  阅读(11015)  评论(3编辑  收藏  举报