myBatis + SpringMVC上传、下载文件

SpringMVC+Mybatis+SqlServer整合实战:增删改查与文件上传下载完整示例 对于数据库不支持的类型(如枚举、JSON),可通过实现双向转换。@Override// 存储 code 字段@Override注册方式:所有表结构变更应以.sql脚本形式保存,便于复用和审计。-- 创建触发器自动更新updated_atON usersASBEGINEND;逻辑分析:UNIQUE约束保障邮箱唯一;实现域完整性;BIT类型表示布尔值(0/1);提供高精度UTC时间;- 触发器确保每次更新都能刷新时间戳字段。 阅读详情

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



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

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

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

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

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

 

1.  前期准备

 使用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.1 html的form表单写法
Html代码   收藏代码
  1. <form action="<c:url value='addAction.do' />" method="post" enctype="multipart/form-data">        
  2.     <table>  
  3.         <tr>  
  4.             <td width="100" align="right">照片:</td>  
  5.             <td><input type="file" name="studentPhoto"/></td>  
  6.         </tr>  
  7.     </table>  
  8.     <input type="submit">  
  9. </form>  
 

 

 

1.2 action方法
Java代码   收藏代码
  1. /** 
  2.  * 新增 - 提交 
  3.  */  
  4. @RequestMapping(value = "addAction.do")  
  5. public String add_action(ModelMap model, StudentForm form) {  
  6.   
  7. }  
 

 

 

1.3 StudentForm类
Java代码   收藏代码
  1. package liming.student.manager.web.model;  
  2.   
  3. import org.springframework.web.multipart.MultipartFile;  
  4.   
  5. public class StudentForm extends GeneralForm {  
  6.   
  7.     private String studentName;  
  8.     private int studentSex;  
  9.     private String studentBirthday;  
  10.     private MultipartFile studentPhoto;  
  11.   
  12. }  
 

 

 

 

1.4 创建PHOTO_TBL
Sql代码   收藏代码
  1. CREATE TABLE PHOTO_TBL  
  2. (  
  3.    PHOTO_ID     VARCHAR(100) PRIMARY KEY,  
  4.    PHOTO_DATA   LONGBLOB,  
  5.    FILE_NAME    VARCHAR(10)  
  6. );  
 

 

 

1.5  PhotoMapper接口
Java代码   收藏代码
  1. @Repository  
  2. @Transactional  
  3. public interface PhotoMapper {  
  4.   
  5.     public void createPhoto(PhotoEntity entity);  
  6.   
  7.     public int deletePhotoByPhotoId(String photoId);  
  8.   
  9.     public int updatePhotoDate(@Param("photoId") String photoId, @Param("photoDate") byte[] photoDate);  
  10.   
  11.     public PhotoEntity getPhotoEntityByPhotoId(String photoId);  
  12.   
  13. }  
 

 

 

 

1.6  PhotoMapper.xml文件

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

 

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="liming.student.manager.data.PhotoMapper">  
  4.     <resultMap type="liming.student.manager.data.model.PhotoEntity" id="photoMapper_resultMap_photoEntity">  
  5.         <id property="photoId"           column="PHOTO_ID"       javaType="String" jdbcType="VARCHAR" />  
  6.         <result property="photoData" column="PHOTO_DATA"     javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler" />  
  7.         <result property="fileName"  column="FILE_NAME"      javaType="String" jdbcType="VARCHAR" />  
  8.     </resultMap>  
  9.       
  10.     <insert id="createPhoto" parameterType="liming.student.manager.data.model.PhotoEntity">  
  11.         <selectKey keyProperty="photoId" resultType="String" order="BEFORE">  
  12.             select nextval('photo')  
  13.         </selectKey>  
  14.         INSERT INTO PHOTO_TBL(PHOTO_ID,  
  15.                               PHOTO_DATA,  
  16.                               FILE_NAME)  
  17.         VALUES(#{photoId, jdbcType=VARCHAR},  
  18.                #{photoData, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  19.                #{fileName, jdbcType=VARCHAR})  
  20.     </insert>  
  21.       
  22.     <delete id="deletePhotoByPhotoId">  
  23.         DELETE FROM PHOTO_TBL  
  24.               WHERE PHOTO_ID = #{photoId, jdbcType=VARCHAR}  
  25.     </delete>  
  26.       
  27.     <update id="updatephotoData" >  
  28.         UPDATE PHOTO_TBL   
  29.            SET PHOTO_DATA = #{photoData, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  30.                FILE_NAME = #{fileName, jdbcType=VARCHAR}  
  31.          WHERE PHOTO_ID = #{photoId, jdbcType=VARCHAR}  
  32.     </update>  
  33.           
  34.     <select id="getPhotoEntityByPhotoId" resultMap="photoMapper_resultMap_photoEntity">  
  35.         SELECT PHOTO_ID,  
  36.                PHOTO_DATA,  
  37.                FILE_NAME  
  38.           FROM PHOTO_TBL  
  39.          WHERE PHOTO_ID = #{photoId, jdbcType=VARCHAR}  
  40.     </select>  
  41. </mapper>  
 
1.7 spring配置文件

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

Xml代码   收藏代码
  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  2.     <property name="maxUploadSize" value="1073741824" />  
  3. </bean>  
 

 

 

2. 将文件到服务器上

Java代码   收藏代码
  1. private static final String uploadFilePath = "d:\\temp_upload_file\\";  
  2.   
  3. /** 
  4.  * 新增 - 提交 – 只保存文件到服务器上 
  5.  */  
  6. @RequestMapping(value = "addAction.do")  
  7. public String add_action(ModelMap model, StudentForm form) {  
  8. try {  
  9.         MultipartFile uploadFile = form.getStudentPhoto();  
  10.         String filename = uploadFile.getOriginalFilename();  
  11.         InputStream is = uploadFile.getInputStream();  
  12.         // 如果服务器已经存在和上传文件同名的文件,则输出提示信息  
  13.         File tempFile = new File(uploadFilePath + filename);  
  14.         if (tempFile.exists()) {  
  15.             boolean delResult = tempFile.delete();  
  16.             System.out.println("删除已存在的文件:" + delResult);  
  17.         }  
  18.         // 开始保存文件到服务器  
  19.         if (!filename.equals("")) {  
  20.             FileOutputStream fos = new FileOutputStream(uploadFilePath + filename);  
  21.             byte[] buffer = new byte[8192]; // 每次读8K字节  
  22.             int count = 0;  
  23.             // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中  
  24.             while ((count = is.read(buffer)) > 0) {  
  25.                 fos.write(buffer, 0, count); // 向服务端文件写入字节流  
  26.             }  
  27.             fos.close(); // 关闭FileOutputStream对象  
  28.             is.close(); // InputStream对象  
  29.         }  
  30.     } catch (FileNotFoundException e) {  
  31.         e.printStackTrace();  
  32.     } catch (IOException e) {  
  33.         e.printStackTrace();  
  34.     }  
  35. }  
 

 

 

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

Java代码   收藏代码
  1. /** 
  2.  * 新增 - 提交 – 保存文件到数据库 
  3.  */  
  4. @RequestMapping(value = "addAction.do")  
  5. public String add_action(ModelMap model, StudentForm form) {  
  6.     InputStream is = form.getStudentPhoto().getInputStream();  
  7.     byte[] studentPhotoData = new byte[(int) form.getStudentPhoto().getSize()];  
  8.     is.read(studentPhotoData);  
  9.     String fileName = form.getStudentPhoto().getOriginalFilename();  
  10.     PhotoEntity photoEntity = new PhotoEntity();  
  11.     photoEntity.setPhotoData(studentPhotoData);  
  12.     photoEntity.setFileName(fileName);  
  13.     this.photoMapper.createPhoto(photoEntity);  
  14. }  
 

 

 

4.下载文件

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

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

 

Java代码   收藏代码
  1. @RequestMapping(value = "downPhotoById")  
  2. public void downPhotoByStudentId(String id, final HttpServletResponse response){  
  3.     PhotoEntity entity = this.photoMapper.getPhotoEntityByPhotoId(id);  
  4.     byte[] data = entity.getPhotoData();  
  5.     String fileName = entity.getFileName()== null ? "照片.png" : entity.getFileName();  
  6.     fileName = URLEncoder.encode(fileName, "UTF-8");  
  7.     response.reset();  
  8.     response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
  9.     response.addHeader("Content-Length", "" + data.length);  
  10.     response.setContentType("application/octet-stream;charset=UTF-8");  
  11.     OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
  12.     outputStream.write(data);  
  13.     outputStream.flush();  
  14.     outputStream.close();  
  15. }  

 

Html代码   收藏代码
  1. <a href="<%=request.getContextPath() %>/downPhotoById.do?id=8000001">下载照片</a>  
 

 

 

5. 显示byte图片文件

Java代码   收藏代码
  1. @RequestMapping(value = "getPhotoById")  
  2. public void getPhotoById (String id, final HttpServletResponse response){  
  3.     PhotoEntity entity = this.photoMapper.getPhotoEntityByPhotoId(id);  
  4.     byte[] data = entity.getPhotoData();  
  5.     response.setContentType("image/jpeg");  
  6.     response.setCharacterEncoding("UTF-8");  
  7.     OutputStream outputSream = response.getOutputStream();  
  8.     InputStream in = new ByteArrayInputStream(data);  
  9.     int len = 0;  
  10.     byte[] buf = new byte[1024];  
  11.     while ((len = in.read(buf, 0, 1024)) != -1) {  
  12.         outputSream.write(buf, 0, len);  
  13.     }  
  14.     outputSream.close();  
  15. }  
 
Html代码   收藏代码
  1. <img src="<%=request.getContextPath() %>/getPhotoById.do?id=8000001"/>  
 

 

 

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

Java代码   收藏代码
  1. @RequestMapping(value = "getPhotoId")  
  2. public void getPhotoById (String id, int width, int height, final HttpServletResponse response){  
  3.     PhotoEntity entity = this.photoMapper.getPhotoEntityByPhotoId(id);  
  4.     byte[] data = entity.getPhotoData();  
  5.     if (width != 0 && height != 0) {  
  6.         data = scaleImage(data, width, height);  
  7.     }  
  8.     response.setContentType("image/jpeg");  
  9.     response.setCharacterEncoding("UTF-8");  
  10.     OutputStream outputSream = response.getOutputStream();  
  11.     InputStream in = new ByteArrayInputStream(data);  
  12.     int len = 0;  
  13.     byte[] buf = new byte[1024];  
  14.     while ((len = in.read(buf, 0, 1024)) != -1) {  
  15.         outputSream.write(buf, 0, len);  
  16.     }  
  17.     outputSream.close();  
  18. }  
  19.   
  20. public static byte[] scaleImage(byte[] data, int width, int height) throws IOException {  
  21.     BufferedImage buffered_oldImage = ImageIO.read(new ByteArrayInputStream(data));  
  22.     int imageOldWidth = buffered_oldImage.getWidth();  
  23.     int imageOldHeight = buffered_oldImage.getHeight();  
  24.     double scale_x = (double) width / imageOldWidth;  
  25.     double scale_y = (double) height / imageOldHeight;  
  26.     double scale_xy = Math.min(scale_x, scale_y);  
  27.     int imageNewWidth = (int) (imageOldWidth * scale_xy);  
  28.     int imageNewHeight = (int) (imageOldHeight * scale_xy);  
  29.     BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);  
  30.     buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);  
  31.     buffered_newImage.getGraphics().dispose();  
  32.     ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();  
  33.     ImageIO.write(buffered_newImage, "jpeg", outPutStream);  
  34.     return outPutStream.toByteArray();  
  35. }  
 
Html代码   收藏代码
  1. <img src="<%=request.getContextPath() %>/getPhotoById.do?id=8000001&width=300&height=300"/>  
 
MyBatis与SpringMVC相结合实现文件上传、下载功能 主要介绍了MyBatis与SpringMVC相结合实现文件上传、下载功能的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 立即下载

相关推荐

【Anaconda】conda国内镜像源快速配置指南(清华/阿里云)

本文详细介绍了如何为Anaconda配置国内镜像源(清华/阿里云),以显著提升conda包下载速度并减少安装失败率。通过分步指南和实用技巧,帮助开发者快速完成配置,优化Python开发环境。

weixin_33725722的博客 1488

使用ajax执行上传的功能

/** * 使用FormData */ $("#formId").click(function(){ var formdata = new FormData($("#formId")[0]); fromdata.append('key','value'); $.ajax({ url: "url", type: "POST", ...

PJF1501105594的博客 324

操作系统知识点汇总(王道)

操作系统不论是就业还是升学都是核心的一门课程,对于大部分工科更是必修课程。本文章是对《王道操作系统》所有知识点的总结笔记,以供大家学习以及在备考期间复习使用。让我们一起把知识往脑子里旋好吗!!!......

S mile0804的博客 5万+

SpringBoot+MyBatisPlus(7)—— 文件上传和下载

文件上传和下载

Archer__13的博客 1158

智能车赛道识别:八邻域算法的实战解析与优化

本文深入解析了智能车赛道识别中八邻域算法的核心原理与实战优化。作为兼顾性能与稳定性的经典方案,该算法通过模拟探险家环顾八方的策略,能精准追踪弯道与直道边界。文章详细拆解了代码逻辑,并提供了边界平滑、异常处理及应对十字路口、环岛等复杂场景的关键优化策略,助力开发者提升智能车视觉系统的鲁棒性与实时性。

weixin_29228781的博客 265

射频电源与等离子体技术:原理、应用与优化策略

射频电源(RF Power Supply)作为高频交流电信号发生器,在半导体制造和材料处理中扮演关键角色。其核心原理是通过高频电场激发气体产生等离子体,这种电离气体包含电子、离子和活性基团,具有独特的非平衡特性。技术价值体现在等离子体密度和电子温度的可控性上,使得在刻蚀和沉积工艺中能精确调控材料处理效果。应用场景广泛覆盖PECVD、深槽刻蚀等工业流程,其中13.56MHz ISM频段因其全球合规性成为行业标准。优化策略包括双频驱动和阻抗匹配网络设计,可显著提升工艺均匀性和设备效率。

weixin_29163797的博客 391

Springboot+MybatisPlus实现从数据库保存的路径下载文件(2)

还是用上次文件上传的数据库测试 文件上传: Springboot+MybatisPlus实现文件上传到服务器并保存路径到数据库(1)_HackAzrael的专栏-优快云博客首先建立测试用的数据库CREATE TABLE `file` ( `id` bigint NOT NULL COMMENT '主键', `filename` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件..

Bummon的学习随笔 991

【uni-app】PDA扫码枪获取扫码数据APP(通俗易懂),聚焦频繁弹软键盘输入法等各种坑完美解决方法,附完整代码

uniapp PDA扫码枪获取扫码数据APP(通俗易懂),频繁弹软键盘等各种坑完美解决方法

coderYYY的博客 7422

Mybatis框架视频教程

本课程内容为JAVA后端开发框架mybatis ,本课程结合大量实践案例 将mybatis的应用场景和方法进行详细的展示 ,学员可以通过课程快速掌握mybatis框架的原理和应用

【C++/嵌入式梳理】bootloader

【C++/嵌入式笔试面试八股】bootloader

Hi 1212

基于Simulink的电动车PMSM能量泄放与回收系统仿真设计

摘要 本文设计了一个基于Simulink的电动车PMSM能量泄放与回收系统仿真模型。系统采用分层建模方案,包含永磁同步电机(PMSM)矢量控制、电池管理和泄放功率计算等核心模块。通过详细的参数计算和MATLAB脚本实现,模拟了电动车在制动时的能量回收过程。重点研究了泄放电阻的控制策略,提出基于母线电压和电池SOC的多目标优化算法,确保系统在保护硬件安全的同时最大化能量回收效率。仿真模型包含完整的数学推导和模块搭建指南,为电动车能量管理系统设计提供了有效的仿真验证平台。

huanghm88的专栏 195

Spring+SpringMvc+Mybatis+多个文件上传,显示与下载

Spring+SpringMvc+Mybatis+多个文件上传与下载 关于ssm整合请看我的第一篇,这里只讲文件上传与下载 首先加入相关依赖: &lt;dependency&gt; &lt;groupId&gt;commons-fileupload&lt;/groupId&gt; &lt;artifactId&gt;commons-fileupload&lt;/ar...

爱码士 的博客 1359

信息传输仿真:卫星通信系统仿真_(12).基于SystemVue的卫星通信仿真

SystemVue是Cadence公司开发的一款用于系统级设计和仿真的软件工具。它主要用于无线通信系统的设计和验证,特别是在卫星通信、雷达、射频和微波通信等领域。SystemVue提供了一个集成的环境,用户可以通过拖拽和连接各种预定义的模块来构建复杂的通信系统模型,从而进行性能分析和优化。

2401_87715305的博客 1370

SpringMVC整合Mybatis之文件上传与下载

工程结构 第一步: 导入commons-fileupload-1.3.1.jar和commons-io-2.4.jar以及SpringMVC与Mybatis的整合jar包 第二步:在applicationContext.xml中配置文件上传的bean 5242880 单文件上传 index.jsp 单文件上传

nuoWei_SenLin的博客 1万+

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

springmvc文件上传到mysql_MyBatis与SpringMVC相结合实现文件上传、下载功能

环境:maven+SpringMVC + Spring + MyBatis + MySql本文主要说明如何使用input上传文件到服务器指定目录,或保存到数据库中;如何从数据库下载文件,和显示图像文件并实现缩放。将文件存储在数据库中,一般是存文件的byte数组,对应的数据库数据类型为blob。首先要创建数据库,此处使用MySql数据库。注意:文中给出的代码多为节选重要片段,并不齐全。1. 前期准备...

weixin_34026053的博客 413

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

上一篇: 上传文件到ftp(apach方法)
下一篇: Freemarker简单总结
ZHA0KAl
博客等级 码龄16年 26粉丝 35原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值