首页 文章资讯内容详情

myBatis + SpringMVC上传、下载文件

2026-06-01 2 花语

本文内容纲要:

-MyBatis学习之一、MyBatis简介与配置MyBaits+Spring+MySql -使用Eclipse构建Maven的SpringMVC项目 -2.将文件到服务器上 -3.将文件上传到数据库中 -4.下载文件 -5.显示byte图片文件 -6.按长宽等比例缩放图片

摘自:http://limingnihao.iteye.com/blog/1069503

环境:maven+SpringMVC+Spring+MyBatis+MySql

本文主要说明如何使用input上传文件到服务器指定目录,或保存到数据库中;如何从数据库下载文件,和显示图像文件并实现缩放。

将文件存储在数据库中,一般是存文件的byte数组,对应的数据库数据类型为blob。

首先要创建数据库,此处使用MySql数据库。

注意:文中给出的代码多为节选重要片段,并不齐全。

前期准备

使用maven创建一个springMVC+spring+mybatis+mysql的项目。

关于如何整合Spring+mybatis+mysql,请见MyBatis简介与配置MyBatis+Spring+MySql:

MyBatis学习之一、MyBatis简介与配置MyBaits+Spring+MySql

关于SpringMVC环境的搭建请见:使用Eclipse构建Maven的SpringMVC项目:

使用Eclipse构建Maven的SpringMVC项目

在前台html中,form的enctype为multipart/form-data。注意input、select的name要和StudentForm中成员一一对应。

上传的url为addAction.do,此action方法的参数中使用StudentForm来映射提交的数据。此时就可以获取到提交的文件的数据。然后我们就对文件进行操作。

创建PHOTO_TBL表:PHOTO_DATA字段用于存放文件,类型为MyBatis的longblob;然后写Mapper的Java接口PhotoMapper:包括增删改查;mapper的xml文件:对应JAVA接口的sql语句。

并且需要Spring配置文件添加一个bean的声明。

下面给出html、action、StudentForm的代码片段;创建PHOTO_TBL表的sql、PhotoMapper.java接口代码、PhotoMapper.xml文件代码。

1.1html的form表单写法

Html代码

照片: 1.2action方法

Java代码

/** *新增-提交 */ @RequestMapping(value="addAction.do") publicStringadd_action(ModelMapmodel,StudentFormform){ } 1.3StudentForm类

Java代码

packageliming.student.manager.web.model; importorg.springframework.web.multipart.MultipartFile; publicclassStudentFormextendsGeneralForm{ privateStringstudentName; privateintstudentSex; privateStringstudentBirthday; privateMultipartFilestudentPhoto; } 1.4创建PHOTO_TBL

Sql代码

CREATETABLEPHOTO_TBL ( PHOTO_IDVARCHAR(100)PRIMARYKEY, PHOTO_DATALONGBLOB, FILE_NAMEVARCHAR(10) ); 1.5PhotoMapper接口

Java代码

@Repository @Transactional publicinterfacePhotoMapper{ publicvoidcreatePhoto(PhotoEntityentity); publicintdeletePhotoByPhotoId(StringphotoId); publicintupdatePhotoDate(@Param("photoId")StringphotoId,@Param("photoDate")byte[]photoDate); publicPhotoEntitygetPhotoEntityByPhotoId(StringphotoId); } 1.6PhotoMapper.xml文件

包括增、删、改、查。其中新增中的photoId使用的是mysql自定义函数自动生成主键。在操作blob时需要制定typeHandler为"org.apache.ibatis.type.BlobTypeHandler。insert、update时参数后面需要指定,resultMap中需要指定。

Xml代码

selectnextval(photo) INSERTINTOPHOTO_TBL(PHOTO_ID, PHOTO_DATA, FILE_NAME) VALUES(#{photoId,jdbcType=VARCHAR}, #{photoData,javaType=byte[],jdbcType=BLOB,typeHandler=org.apache.ibatis.type.BlobTypeHandler}, #{fileName,jdbcType=VARCHAR}) DELETEFROMPHOTO_TBL WHEREPHOTO_ID=#{photoId,jdbcType=VARCHAR} UPDATEPHOTO_TBL SETPHOTO_DATA=#{photoData,javaType=byte[],jdbcType=BLOB,typeHandler=org.apache.ibatis.type.BlobTypeHandler}, FILE_NAME=#{fileName,jdbcType=VARCHAR} WHEREPHOTO_ID=#{photoId,jdbcType=VARCHAR} SELECTPHOTO_ID, PHOTO_DATA, FILE_NAME FROMPHOTO_TBL WHEREPHOTO_ID=#{photoId,jdbcType=VARCHAR} 1.7spring配置文件

需要Spring配置文件添加一个org.springframework.web.multipart.commons.CommonsMultipartResolver的bean的声明。

Xml代码

2.将文件到服务器上

Java代码

privatestaticfinalStringuploadFilePath="d:\\temp_upload_file\\"; /** *新增-提交–只保存文件到服务器上 */ @RequestMapping(value="addAction.do") publicStringadd_action(ModelMapmodel,StudentFormform){ try{ MultipartFileuploadFile=form.getStudentPhoto(); Stringfilename=uploadFile.getOriginalFilename(); InputStreamis=uploadFile.getInputStream(); //如果服务器已经存在和上传文件同名的文件,则输出提示信息 FiletempFile=newFile(uploadFilePath+filename); if(tempFile.exists()){ booleandelResult=tempFile.delete(); System.out.println("删除已存在的文件:"+delResult); } //开始保存文件到服务器 if(!filename.equals("")){ FileOutputStreamfos=newFileOutputStream(uploadFilePath+filename); byte[]buffer=newbyte[8192];//每次读8K字节 intcount=0; //开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中 while((count=is.read(buffer))>0){ fos.write(buffer,0,count);//向服务端文件写入字节流 } fos.close();//关闭FileOutputStream对象 is.close();//InputStream对象 } }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } }

3.将文件上传到数据库中

Java代码

/** *新增-提交–保存文件到数据库 */ @RequestMapping(value="addAction.do") publicStringadd_action(ModelMapmodel,StudentFormform){ InputStreamis=form.getStudentPhoto().getInputStream(); byte[]studentPhotoData=newbyte[(int)form.getStudentPhoto().getSize()]; is.read(studentPhotoData); StringfileName=form.getStudentPhoto().getOriginalFilename(); PhotoEntityphotoEntity=newPhotoEntity(); photoEntity.setPhotoData(studentPhotoData); photoEntity.setFileName(fileName); this.photoMapper.createPhoto(photoEntity); }

4.下载文件

下载文件需要将byte数组还原成文件。

首先使用mybatis将数据库中的byte数组查出来,指定文件名(包括格式)。然后使用OutputStream将文件输入

Java代码

@RequestMapping(value="downPhotoById") publicvoiddownPhotoByStudentId(Stringid,finalHttpServletResponseresponse){ PhotoEntityentity=this.photoMapper.getPhotoEntityByPhotoId(id); byte[]data=entity.getPhotoData(); StringfileName=entity.getFileName()==null?"照片.png":entity.getFileName(); fileName=URLEncoder.encode(fileName,"UTF-8"); response.reset(); response.setHeader("Content-Disposition","attachment;filename=\""+fileName+"\""); response.addHeader("Content-Length",""+data.length); response.setContentType("application/octet-stream;charset=UTF-8"); OutputStreamoutputStream=newBufferedOutputStream(response.getOutputStream()); outputStream.write(data); outputStream.flush(); outputStream.close(); }

Html代码

下载照片

5.显示byte图片文件

Java代码

@RequestMapping(value="getPhotoById") publicvoidgetPhotoById(Stringid,finalHttpServletResponseresponse){ PhotoEntityentity=this.photoMapper.getPhotoEntityByPhotoId(id); byte[]data=entity.getPhotoData(); response.setContentType("image/jpeg"); response.setCharacterEncoding("UTF-8"); OutputStreamoutputSream=response.getOutputStream(); InputStreamin=newByteArrayInputStream(data); intlen=0; byte[]buf=newbyte[1024]; while((len=in.read(buf,0,1024))!=-1){ outputSream.write(buf,0,len); } outputSream.close(); }

Html代码

/getPhotoById.do?id=8000001"/">

6.按长宽等比例缩放图片

Java代码

@RequestMapping(value="getPhotoId") publicvoidgetPhotoById(Stringid,intwidth,intheight,finalHttpServletResponseresponse){ PhotoEntityentity=this.photoMapper.getPhotoEntityByPhotoId(id); byte[]data=entity.getPhotoData(); if(width!=0&&height!=0){ data=scaleImage(data,width,height); } response.setContentType("image/jpeg"); response.setCharacterEncoding("UTF-8"); OutputStreamoutputSream=response.getOutputStream(); InputStreamin=newByteArrayInputStream(data); intlen=0; byte[]buf=newbyte[1024]; while((len=in.read(buf,0,1024))!=-1){ outputSream.write(buf,0,len); } outputSream.close(); } publicstaticbyte[]scaleImage(byte[]data,intwidth,intheight)throwsIOException{ BufferedImagebuffered_oldImage=ImageIO.read(newByteArrayInputStream(data)); intimageOldWidth=buffered_oldImage.getWidth(); intimageOldHeight=buffered_oldImage.getHeight(); doublescale_x=(double)width/imageOldWidth; doublescale_y=(double)height/imageOldHeight; doublescale_xy=Math.min(scale_x,scale_y); intimageNewWidth=(int)(imageOldWidth*scale_xy); intimageNewHeight=(int)(imageOldHeight*scale_xy); BufferedImagebuffered_newImage=newBufferedImage(imageNewWidth,imageNewHeight,BufferedImage.TYPE_INT_RGB); buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth,imageNewHeight,BufferedImage.SCALE_SMOOTH),0,0,null); buffered_newImage.getGraphics().dispose(); ByteArrayOutputStreamoutPutStream=newByteArrayOutputStream(); ImageIO.write(buffered_newImage,"jpeg",outPutStream); returnoutPutStream.toByteArray(); }

Html代码

/getPhotoById.do?id=8000001&width=300&height=300"/">

7

0

分享到:

dwr学习之一、dwr+spring的简单集成|MyBatis学习之四、MyBatis配置文件

2011-06-0313:58 浏览11476 评论(6) 分类:编程语言 相关推荐 评论

6楼zqb666kkk2013-12-23

PhotoEntity呢?

5楼zqb666kkk2013-12-23

photoEntity.setPhotoData(studentPhotoData);

你这句话有问题吧

实体类里是privateMultipartFilestudentPhoto;

MultipartFile类型的

set的时候byte[]类型

类型不符合编译都通不过的

4楼eye_dxj2013-10-30

outputStream.flush();

3楼ddnzero2013-05-21

PhotoMapper.xml文件这个正需要啊感谢~

2楼我是菜鸟1号2013-03-29

貌似没看到PhotoEntity这个类吧...

1楼幸福人生2011-09-23

很好,代码直接拷贝就可以,支持一下!

本文内容总结:MyBatis学习之一、MyBatis简介与配置MyBaits+Spring+MySql,使用Eclipse构建Maven的SpringMVC项目,2.将文件到服务器上,3.将文件上传到数据库中,4.下载文件,5.显示byte图片文件,6.按长宽等比例缩放图片,

原文链接:https://www.cnblogs.com/wuyifu/p/3627516.html