SpringMVC上传文件总结
如果是maven项目 需要在pom.xml文件里面引入下面两个jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
版本可以选择最新的版本。
如果不是,需要手动添加jar包的话,需要导入下面两个jar包:
1、commons-fileupload-1.2.2.jar
2、commons-io-2.0.1.jar
jar包引入后,我们接下来需要去配置一下配置文件,在配置文件里面加入下面内容:
<!-- 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>
接下来是上传页面jsp
<%@ 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="file" name="uploadfile">(如果是多文件可以继续添加多个file类型的input)
<input type="submit" value="上传">
</form>
</body>
</html>
Java类处理file
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";
}
}
}
如果是多文件的话,原理和上面相同,但是接收参数我们是用的CommonsMultipartFile数组
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上传文件总结的更多相关文章
- springmvc上传文件,抄别人的
		
SpringMVC中的文件上传 分类: SpringMVC 2012-05-17 12:55 26426人阅读 评论(13) 收藏 举报 stringuserinputclassencoding 这是 ...
 - 2. SpringMVC 上传文件操作
		
1.创建java web项目:SpringMVCUploadDownFile 2.在项目的WebRoot下的WEB-INF的lib包下添加如下jar文件 com.springsource.com.mc ...
 - 使用springMVC上传文件
		
control层实现功能: @RequestMapping(value="upload2") public String upLoad2(HttpServletRequest re ...
 - SpringMVC上传文件(图片)并保存到本地
		
SpringMVC上传文件(图片)并保存到本地 小记一波~ 基本的MVC配置就不展示了,这里给出核心代码 在spring-mvc的配置文件中写入如下配置 <bean id="multi ...
 - SpringMVC 上传文件 MultipartFile 转为 File
		
在使用 SpringMVC 上传文件时,接收到的文件格式为 MultipartFile,但是在很多场景下使用都需要File格式的文件,记录下以便日后使用. 以下mFile为MultipartFile文 ...
 - springmvc 上传文件时的错误
		
使用springmvc上传文件一直失败,文件参数一直为null, 原来是配置文件没写成功. <bean id="multipartResolver" class=" ...
 - SpringMVC上传文件的三种方式(转)
		
直接上代码吧,大伙一看便知 这时:commonsmultipartresolver 的源码,可以研究一下 http://www.verysource.com/code/2337329_1/common ...
 - SpringMVC上传文件的三种方式
		
直接上代码吧,大伙一看便知 这时:commonsmultipartresolver 的源码,可以研究一下 http://www.verysource.com/code/2337329_1/common ...
 - SpringMVC上传文件
		
SpringMVC中上传文件还是比较方便的,Spring内置了一些上传文件的支持类,不需要复杂的操作即可上传文件. 文件上传需要两个jar支持,一个是commons-fileupload.jar和co ...
 
随机推荐
- springfox-swagger
			
swagger简介 swagger确实是个好东西,可以跟据业务代码自动生成相关的api接口文档,尤其用于restful风格中的项目,开发人员几乎可以不用专门去维护rest api,这个框架可以自动为你 ...
 - 创建本地repo源
			
1,保留rpm包 yum 安装时保留包至指定目录 编辑/etc/yum.conf 将keepcache的值设置为1: 2,使用插件 1,yum-plugin-downloadonly插件 sudo y ...
 - QT:QSS ID选择器无效
			
我正在学习使用Qt样式表给我的应用程序添加不同的样式.我上网看了看Qt文档,上面说你可以使用一种ID选择器,它可以把主题应用到某些对象上.我就是这样实现这个特性的: QPushButton#butto ...
 - 14、SpinBox与Horizontal Scroll Bar
			
设定这两个控件maximum为100,转到槽 void MainWindow::on_horizontalSlider_valueChanged(int value) { ui->spinBox ...
 - C# 1.0(2002)
			
序言 C# 1可以看做2001年Java语言的升级版. 主要功能 类 结构 接口 事件 属性 委托 表达式 语句 特性 值类型和引用类型 装箱和拆箱 资料
 - APIView源码与Request源码分析
			
一.APIView源码分析 1.安装djangorestframework 2.使用 drf是基于cbv view的封装,所以必须写cbv ①第一步:写视图,必须写cbv 路由配置: from res ...
 - Linux 压缩方式测试
			
测试方法 使用 python 的 Faker 第三方包伪造数据,写入文件 test.txt 复制 test.txt 内容为 test2.txt ,将 test2.txt 的内容重定向到 test.tx ...
 - 剑指offer:关于复制构造函数
			
1:首先参看代码: #include "stdafx.h" #include "iostream" using namespace std; class A { ...
 - mosquitto订阅发布参数详解
			
特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...
 - CentOS 7,使用yum安装Nginx
			
https://www.centos.bz/2018/01/centos-7%EF%BC%8C%E4%BD%BF%E7%94%A8yum%E5%AE%89%E8%A3%85nginx/ 文章目录 [隐 ...