SpringMVC 学习笔记(五)
47. 尚硅谷_佟刚_SpringMVC_文件上传.avi
参看博客https://www.cnblogs.com/hanfeihanfei/p/7931758.html相当的经典
我是陌生人
关于SpringMVC的文件上传
关于文件的上传,之前写过2篇文章,基于Struts2框架,下面给出文章链接:
《关于Struts2的文件上传》:http://www.cnblogs.com/lichenwei/p/3927964.html
《关于Struts2的多文件上传》:http://www.cnblogs.com/lichenwei/p/3928200.html
其实文件上传的原理都是一样的,基于SpringMVC的文件上传实现要比Struts2要来得简单许多。
好了,废话不多说,直接切入主题吧,关于上传原理不了解的朋友,可以轻戳上面2篇文章的链接。
1、万变不离其宗,要实现文件的上传需要对应的JAR包:
1、commons-fileupload-1.2.2.jar
2、commons-io-2.0.1.jar
2、要实现SpringMVC的文件上传,需要配置一下文件:
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="-1" />
</bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到XXX页面 -->
<prop
key="org.springframework.web.multipart.MaxUploadSizeExceededException">跳转XXX页面</prop>
</props>
</property>
</bean>
3、上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="<%=basePath%>upload.do" method="post"
enctype="multipart/form-data">
<input type="hidden" name="tuzi" value="tuzi">
上传文件:<input type="file" name="uploadfile">
<input type="submit" value="上传">
</form>
</body>
</html>
4、文件处理类:
package lcw.controller; import java.io.File;
import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
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; /**
*
* 文件上传处理类
*
*/
@Controller
public class FileController { //单文件上传
@RequestMapping(value = "/upload.do")
public String queryFileData(
@RequestParam("uploadfile") CommonsMultipartFile file,
HttpServletRequest request) {
// MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
if (!file.isEmpty()) {
String type = file.getOriginalFilename().substring(
file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
String path = request.getSession().getServletContext()
.getRealPath("/upload/" + filename);// 存放位置
File destFile = new File(path);
try {
// FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
FileUtils
.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_ok.jsp";
} else {
return "redirect:upload_error.jsp";
}
}
}
5、看一下实现效果图:


6、再来看下关于多文件上传,其实原理还是一样,只不过是把CommonsMultipartFile类对象换成一个数组,然后用一个for循环去遍历这个数组,并分别存入。
package lcw.controller; import java.io.File;
import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
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; /**
*
* 文件上传处理类
*
*/
@Controller
public class FileController { //单文件上传
@RequestMapping(value = "/upload.do")
public String queryFileData(
@RequestParam("uploadfile") CommonsMultipartFile file,
HttpServletRequest request) {
// MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
if (!file.isEmpty()) {
String type = file.getOriginalFilename().substring(
file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
String path = request.getSession().getServletContext()
.getRealPath("/upload/" + filename);// 存放位置
File destFile = new File(path);
try {
// FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
FileUtils
.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_ok.jsp";
} else {
return "redirect:upload_error.jsp";
}
} //多文件上传
@RequestMapping(value = "/uploads.do")
public String queryFileDatas(
@RequestParam("uploadfile") CommonsMultipartFile[] files,
HttpServletRequest request) {
if (files != null) {
for (int i = 0; i < files.length; i++) {
String type = files[i].getOriginalFilename().substring(
files[i].getOriginalFilename().indexOf("."));// 取文件格式后缀名
String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
String path = request.getSession().getServletContext()
.getRealPath("/upload/" + filename);// 存放位置
File destFile = new File(path);
try {
FileUtils.copyInputStreamToFile(files[i].getInputStream(),
destFile);// 复制临时文件到指定目录下
} catch (IOException e) {
e.printStackTrace();
}
}
return "redirect:upload_ok.jsp";
} else {
return "redirect:upload_error.jsp";
} } }
关于SpringMVC的文件上传
关于文件的上传,之前写过2篇文章,基于Struts2框架,下面给出文章链接:
《关于Struts2的文件上传》:http://www.cnblogs.com/lichenwei/p/3927964.html
《关于Struts2的多文件上传》:http://www.cnblogs.com/lichenwei/p/3928200.html
其实文件上传的原理都是一样的,基于SpringMVC的文件上传实现要比Struts2要来得简单许多。
好了,废话不多说,直接切入主题吧,关于上传原理不了解的朋友,可以轻戳上面2篇文章的链接。
1、万变不离其宗,要实现文件的上传需要对应的JAR包:
1、commons-fileupload-1.2.2.jar
2、commons-io-2.0.1.jar
2、要实现SpringMVC的文件上传,需要配置一下文件:
3、上传页面
4、文件处理类:
5、看一下实现效果图:


6、再来看下关于多文件上传,其实原理还是一样,只不过是把CommonsMultipartFile类对象换成一个数组,然后用一个for循环去遍历这个数组,并分别存入。
7、看下效果图:


作者:Balla_兔子
出处:http://www.cnblogs.com/lichenwei/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!
SpringMVC 学习笔记(五)的更多相关文章
- springMVC学习笔记(五)
一.使用Ajax调用 1.1 Controller返回的类型为text类型的方式. @RequestMapping("/getPerson") public void getPer ...
- SpringMVC学习笔记五:使用converter进行参数数据转换
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6832898.html 一:SpringMVC数据绑定机制 1:request到达SpringMVC框架时,框 ...
- SpringMVC 学习笔记(五) 基于RESTful的CRUD
1.1. 概述 当提交的表单带有_method字段时,通过HiddenHttpMethodFilter 将 POST 请求转换成 DELETE.PUT请求,加上@PathVariable注解从而实现 ...
- SpringMVC学习笔记五:HandlerExceptionResolver异常处理
继承HandlerExceptionResolver自定义异常处理器 控制器ExceptionController.java package com.orange.controller; import ...
- 史上最全的SpringMVC学习笔记
SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...
- SpringMVC学习笔记之二(SpringMVC高级参数绑定)
一.高级参数绑定 1.1 绑定数组 需求:在商品列表页面选中多个商品,然后删除. 需求分析:功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Cont ...
- C#可扩展编程之MEF学习笔记(五):MEF高级进阶
好久没有写博客了,今天抽空继续写MEF系列的文章.有园友提出这种系列的文章要做个目录,看起来方便,所以就抽空做了一个,放到每篇文章的最后. 前面四篇讲了MEF的基础知识,学完了前四篇,MEF中比较常用 ...
- springmvc学习笔记--REST API的异常处理
前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...
- springmvc学习笔记---面向移动端支持REST API
前言: springmvc对注解的支持非常灵活和飘逸, 也得web编程少了以往很大一坨配置项. 另一方面移动互联网的到来, 使得REST API变得流行, 甚至成为主流. 因此我们来关注下spring ...
随机推荐
- ftp上传html文件
在用ftp上传当个html文件时,发现html文件会被压缩成一行,在html中的单行注释将后面的代码都注释掉了,导致网页不能正常访问. 8uftp.FlashFXP.filezilla 在这三个ftp ...
- Rocket - tilelink - AtomicAutomata之二
https://mp.weixin.qq.com/s/XDUtw0uPrVXC4CChbydF_A 分析在透传和代理两种模式下,AtomicAutomata可能出现的问题. 1. 透 ...
- IntelliJ IDEA连接不上数据库 (Connection to testdb@localhost failed. [08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.)
问题提示为: 原因:MySQL数据库版本为8.0以上,需要在URL加上时区,即加上?serverTimezone=GMT 成功后为:
- Vue中将网址、动态网址转为二维码
1. 首先需要安装相关的依赖包 npm install qrcodejs2 --save 或者 npm install qrcode2 --save 这里选择第二种方式进行安装,如图: 2.templ ...
- Java 第十一届 蓝桥杯 省模拟赛 小明的城堡
小明用积木搭了一个城堡. 为了方便,小明在搭的时候用的是一样大小的正方体积本,搭在了一个 n 行 m 列的方格图上,每个积木正好占据方格图的一个小方格. 当然,小明的城堡并不是平面的,而是立体的.小明 ...
- Java实现 LeetCode 94 二叉树的中序遍历
94. 二叉树的中序遍历 给定一个二叉树,返回它的中序 遍历. 示例: 输入: [1,null,2,3] 1 2 / 3 输出: [1,3,2] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? / ...
- Java实现 N的阶乘
import java.util.Scanner; public class n的阶乘 { public static void main(String[] args) { Scanner sc =n ...
- Java实现 LeetCode 5 最长回文子串
5. 最长回文子串 给定一个字符串 s,找到 s 中最长的回文子串.你可以假设 s 的最大长度为 1000. 示例 1: 输入: "babad" 输出: "bab&quo ...
- java实现第七届蓝桥杯七星填数
七星填数 如图[图1.png]所示. 在七角星的14个节点上填入1~14 的数字,不重复,不遗漏. 要求每条直线上的四个数字之和必须相等. 图中已经给出了3个数字. 请计算其它位置要填充的数字,答案唯 ...
- Centos宝塔安装NextCloud
官方版本列表链接:https://download.nextcloud.com/server/releases/ 我下载的是 16.0.6版本,下载链接:https://download.nextcl ...