今天来介绍一个关于SpringMVC框架的文件上传功能。首先我个人感觉SpringMVC框架的文件上传还是要比Struts2框架要好用一些,灵活性更强。因为SpringMVC框架的文件上传有几种不同的实现方式,所以我们先给大家介绍基于CommonsMultipartFile来实现文件上传的功能

1. 大家可以先了解案例实现的效果

 

2. 搭建一下文件上传必备的环境

  • 导入commons-fileupload-13.2.jar,commons-io-2.5.jar
  • 在SpringMVC的配置文件中增加支持文件上传的解析器如果不加入文件上传的解析,那么我们提交的请求会出现HTTP 400的错误

3. 文件上传功能需求

  • 客户端提交的上传文件需要保存到Web服务器指定的目录中
  • 服务器保存的文件名字需要进行一定的修改

4. 功能实现步骤

  • 添加支持文件上传的解析器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.gxa.springmvc.controller"></context:component-scan> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880"></property>
<property name="maxInMemorySize" value="4096"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean> </beans>
  • 编写文件上传的控制器代码
package com.gxa.springmvc.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile; /**
* SpringMVC的文件上次应用
* @author caleb
*
*/
@Controller
@RequestMapping("/upload")
public class FileUploadController { /**
* 单个文件上传
* @throws IOException
*/
@RequestMapping("/singlefileupload")
public void singleFileUpload(@RequestParam(value="file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
long start = System.currentTimeMillis();
String uploadFileName = file.getOriginalFilename();
String savePath = request.getServletContext().getRealPath("/") + "upload";
savePath = savePath.replaceAll("\\\\", "/");
String saveFileName = start + "" + uploadFileName.substring(uploadFileName.lastIndexOf("."));
File dirs = new File(savePath);
if (!dirs.exists()) {
dirs.mkdirs();
}
file.transferTo(new File(dirs, saveFileName));
long end = System.currentTimeMillis();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("上传文件的名称 = " + uploadFileName);
out.println("<p>");
out.println("保存文件的路径 = " + savePath);
out.println("<p>");
out.println("保存文件的名称 = " + saveFileName);
out.println("<p>");
out.println("上传成功的时间 = " + String.valueOf(end - start) + "ms");
out.flush();
out.close();
} }
  • 编写文件上传的html代码,注意表单中需要加入enctype="multipart/form-data"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload/singlefileupload.do" method="post" enctype="multipart/form-data">
<fieldset>
<legend>单个文件上传</legend>
<input type="file" name="file"><input type="submit">
</fieldset>
</form>
</body>
</html>

5. 控制器中代码解读

  • singleFileUpload中的@RequestParam("file") CommonsMultipartFile file
public void singleFileUpload(@RequestParam(value="file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException 

注意:html代码中文件上传域中的name="file"要对应Java代码中@RequestParam("file") CommonsMultipartFile file

  • file.transferTo(new File(dirs, saveFileName)); 封装了解析文件上传的IO流,同时完成将文件保存到服务器的操作
  • 因为在SpringMVC的配置文件中没有添加ViewResolver接口,所以我们就利用比较传统的Servlet API来展示上传成功的信息输出

 源码下载地址:https://pan.baidu.com/s/1eSDZwFg

最新文章

  1. ps技巧
  2. 高性能网站架构设计之缓存篇(6)- Redis 集群(中)
  3. ConcurrentHashMap Put()操作示例代码
  4. sql数据库(资料库)的基本操作
  5. magento-connect-manage出现404或者500内部错误的解决办法
  6. 浅析C#基于TCP协议的SCOKET通信
  7. C# CRC32
  8. on事件绑定阻止冒泡的问题
  9. git 入门宝典
  10. Struts2第十一篇【简单UI标签、数据回显】
  11. Java的注解总结
  12. SPOJ COT3.Combat on a tree(博弈论 Trie合并)
  13. Java-函数式编程(二)Lambda表达式
  14. 【BZOJ1965】[AHOI2005]洗牌(数论)
  15. 2018.10.19 NOIP训练 yk赚钱记(01分数规划)
  16. 【数组】Search Insert Position
  17. 山寨一个std::bind\boost::bind
  18. JDK1.7新特性(1):Switch和数字
  19. bzoj1511 [POI2006]OKR-Periods of Words kmp+乱搞
  20. Lombok 简单入门

热门文章

  1. 十四、.net core(.NET 6)搭建ElasticSearch(ES)系列之给ElasticSearch添加SQL插件和浏览器插件
  2. 女朋友看了也懂的Kafka(下篇)
  3. spring 声明式事务剖析
  4. springboot注解之@ConditionalOnProperty
  5. 对话Apache Hudi VP, 洞悉数据湖的过去现在和未来
  6. ES6中的Map
  7. 屌炸天,像写代码一样写PPT,一个小工具解决
  8. 面试总被问到HTTP缓存机制及原理?看完你就彻底明白了
  9. 解决java socket在传输汉字时出现截断导致乱码的问题
  10. 关于MySql数据库误操作数据找回的办法