springMvc+myBatis上传图片到mySQL数据库

时间:2022-10-15 00:33:26
思路:将前台上传的file存到MutipartFile类型字段中,再将MulipartFile转换为pojo类中的byte[]数组,最后存入数据库longBlob类型字段中
    1、jsp(enctype必须设置为"multipart/form-data")
        <form id="registerForm" action="registerSubmit.action" method="post" enctype="multipart/form-data">
上传头像 <input type="file" id="uploadPhoto" name="uploadPhoto1">
上传头像 <input type="file" id="uploadPhoto2" name="uploadPhoto2">
上传头像 <input type="file" id="uploadPhoto3" name="uploadPhoto3">
<p class="help-block">点击浏览上传您的照片(至少一张,最多可上传三张)</p>
</form>


2、controller
        // 提交注册
@RequestMapping(value = "/registerSubmit.action")
public String registerSubmit(User user,<span style="color:#ff0000;">MultipartFile uploadPhoto1,MultipartFile uploadPhoto2,MultipartFile uploadPhoto3</span>,HttpServletResponse response,HttpServletRequest request,Model model) throws Exception {
String msg = registerService.addUser(user,userBirthdayStr,uploadPhoto1,uploadPhoto2,uploadPhoto3);
return "forward:sociaty.action"; //在跳转之前需判断是否注册成功
}


3、service
    @Override
public String addUser(User user,<span style="color:#ff0000;">MultipartFile  pic1,MultipartFile pic2,MultipartFile pic3</span>) throws Exception {
//上传图片
user.setID(UUID.randomUUID().toString());//设置id
//user还有其他属性,jsp提交的时候已经写入到user,不用再set

//转换图片格式 :MultipartFile --> byte
byte[] b1 = pic1.getBytes();
<span style="white-space:pre"> </span>byte[] b2 = pic2.getBytes();
<span style="white-space:pre"> </span>byte[] b3 = pic3.getBytes();<span style="white-space:pre"> </span>
user.setUploadPhoto1_Byte(b1); //将转换后的byte[]存入到user类中byte[]字段
user.setUploadPhoto2_Byte(b2);
user.setUploadPhoto3_Byte(b3);

registerMapper.addUser(user);
return "success";
}


4、mapper.xml
       sql语句
            <insert id="addUser" parameterType="com.xxx.xxx.User">
insert into 表名
values
( #{uploadPhoto1_Byte,jdbcType=BLOB},#{uploadPhoto2_Byte,jdbcType=BLOB},
#{uploadPhoto3_Byte,jdbcType=BLOB})
</insert>


         设置mysql表中字段类型为blob或 longBlog

5、user类( byte[]类型字段,用来将文件存入数据库
    private byte[] uploadPhoto1_Byte;
private byte[] uploadPhoto2_Byte;
private byte[] uploadPhoto3_Byte;



6、设置mysql配置文件(my-large.ini)中 max_allowed_packet 为4M
        不然的话上传文件超过1M会报错:  

            Packet for query is too large (1117260 > 1048576). You can change this value on the server by

可以先查询一下:show VARIABLES like '%max_allowed_packet%';
修改此变量的值:MySQL安装目录下的my.ini文件中的[mysqld]段中的"max_allowed_packet = 1M",如更改为4M(如果没有这行内容,增加一行),保存,重新启动MySQL服务。现在可以load大于1M的文件了。

有时候命令“SET GLOBAL max_allowed_packet=16*1024*1024”无效,需要使用如下命令:set @@max_allowed_packet=5*1024*1024 

springMvc+myBatis上传图片到mySQL数据库springMvc+myBatis上传图片到mySQL数据库