关于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";
} } }
7、看下效果图:


作者:Balla_兔子
出处:http://www.cnblogs.com/lichenwei/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!
关于SpringMVC的文件上传的更多相关文章
- springmvc图片文件上传接口
springmvc图片文件上传 用MultipartFile文件方式传输 Controller package com.controller; import java.awt.image.Buffer ...
- SpringMVC学习--文件上传
简介 文件上传是web开发中常见的需求之一,springMVC将文件上传进行了集成,可以方便快捷的进行开发. springmvc中对多部件类型解析 在 页面form中提交enctype="m ...
- Spring +SpringMVC 实现文件上传功能。。。
要实现Spring +SpringMVC 实现文件上传功能. 第一步:下载 第二步: 新建一个web项目导入Spring 和SpringMVC的jar包(在MyEclipse里有自动生成spring ...
- SpringMVC之文件上传异常处理
一般情况下,对上传的文件会进行大小的限制.如果超过指定大小时会抛出异常,一般会对异常进行捕获并友好的显示出来.以下用SpringMVC之文件上传进行完善. 首先配置CommonsMultipartRe ...
- springmvc实现文件上传
springmvc实现文件上传 多数文件上传都是通过表单形式提交给后台服务器的,因此,要实现文件上传功能,就需要提供一个文件上传的表单,而该表单就要满足以下3个条件 (1)form表彰的method属 ...
- 【SpringMVC】文件上传Expected MultipartHttpServletRequest: is a MultipartResolver错误解决
本文转载自:https://blog.csdn.net/lzgs_4/article/details/50465617 使用SpringMVC实现文件上传时,后台使用了 MultipartFile类, ...
- 一起学SpringMVC之文件上传
概述 在Web系统开发过程中,文件上传是普遍的功能,本文主要以一个简单的小例子,讲解SpringMVC中文件上传的使用方法,仅供学习分享使用,如有不足之处,还请指正. 文件上传依赖包 如下所示,文件上 ...
- SpringMVC+ajax文件上传实例教程
原文地址:https://blog.csdn.net/weixin_41092717/article/details/81080152 文件上传文件上传是项目开发中最常见的功能.为了能上传文件,必须将 ...
- 6.学习springmvc的文件上传
一.文件上传前提与原理分析 1.文件上传必要前提: 2.文件上传原理分析: 3.需要引入的jar包: 二.传统方式文件上传程序 1.pom.xml <dependency> <gro ...
随机推荐
- 08Vue.js快速入门-Vue综合实战项目
8.1. 前置知识学习 npm 学习 官方文档 推荐资料 npm入门 npm介绍 需要了解的知识点 package.json 文件相关配置选项 npm 本地安装.全局安装.本地开发安装等区别及相关命令 ...
- RabbitMQ中各种消息类型如何处理?
一:消息类型 Map String(含json字符串类型) 二:处理方法 2.1 Map消息 如果发送的消息类型是map类型,可以通过SerializationUtils.deserialize方法将 ...
- Eigen教程(11)
整理下Eigen库的教程,参考:http://eigen.tuxfamily.org/dox/index.html 存储顺序 对于矩阵和二维数组有两种存储方式,列优先和行优先. 假设矩阵: 按行优先存 ...
- [转]mybatis如何直接 执行传入的任意sql语句 并按照顺序取出查询的结果集
原文地址:https://www.cnblogs.com/wuyun-blog/p/5769096.html 需求: 1.直接执行前端传来的任何sql语句,parameterType="St ...
- C语言 · 排列数 · 排列式
蓝桥练习场上不断碰到类似的题,都是一个递归搜索的套路. 算法提高 排列数 时间限制:1.0s 内存限制:256.0MB 问题描述 0.1.2三个数字的全排列有六种,按照字母序排列如下 ...
- <低风险投资之路>读书笔记
书在这里 低风险才能高收益 大的投资收益回撤,是长期高复合收益率的最大杀手 要赚钱先不赔钱 选择合理的投资组合与合理的仓位 盈利的关键不是你买了什么,而是你买了多少.这就是仓位管理的技巧,在确定性盈利 ...
- centOSmini安装教程
最近使用了CentOS发现比Ubuntu更简洁,有些爱上CentOS了 1. 准备一版CentOS安装镜像文件 官网下载地址:http://www.centos.org/download/ 官方有三个 ...
- Go Revel - main函数分析
运行revel命令时,首先会编译整个项目,在编译时,会根据`app.conf`配置文件生成两个源码文件`tmp/main.go`.`routes/routes.go`,其中`main.go`是整个项目 ...
- Android——shape和selector和layer-list的(详细说明 转)
<shape>和<selector>在Android UI设计中经常用到.比如我们要自定义一个圆角Button,点击Button有些效果的变化,就要用到<shape> ...
- Javascript全栈技术架构
https://worktile.com/tech/basic/the-worktile-tech-stack https://worktile.com/tech/basic/worktile-rea ...