四种springmvc上传文件的方法-附带dome
- 结构:
- index.jsp代码:
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form name="Form1" action="upload1" method="post" enctype="multipart/form-data">
文件1:<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
<form name="Form2" action="fileUpload2" method="post" enctype="multipart/form-data">
文件2:<input type="file" name="file"><br>
<input type="submit" value="上传"/>
</form>
</body>
<form name="Form3" action="fileUpload" method="post" enctype="multipart/form-data">
文件3:<input type="file" name="file"><br>
<input type="submit" value="上传"/>
</form>
<form name="Form4" action="springUpload" method="post" enctype="multipart/form-data">
文件4:<input type="file" name="file"><br>
<input type="submit" value="上传"/>
</form>
</html>
- 必配xml
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>t71springmvc</display-name>
<!-- springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
- springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 扫包 -->
<context:component-scan base-package="com.wqk"></context:component-scan>
<!-- 试图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
</bean>
<!-- 第二、三、四种上传的配置多部分文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
</beans>
一、不需要配置xml文件
/**
* 第一种上传:
* @throws IOException
* @throws IllegalStateException
* */
@RequestMapping(value="/upload1", method=RequestMethod.POST)
public String upload1(@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request){
String fileName = file.getOriginalFilename();
System.out.println(fileName);
//获取扩展名
String extension = fileName.substring(fileName.lastIndexOf("."));
//新的文件名 234-135234532l34kjlkj.jpg
String savedFileName = java.util.UUID.randomUUID().toString() + extension;
//设置路径
String folderPath = "E://uimg";
File savedFile = new File(folderPath, savedFileName);
//保存文件
try {
file.transferTo(savedFile);
} catch (IOException e) {
e.printStackTrace();
}
return "index";
}
二、采用file.Transto 来保存上传的文件
/**
* 第二种上传:
* */
/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/fileUpload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException {
long startTime=System.currentTimeMillis();
System.out.println("fileName:"+file.getOriginalFilename());
String path="E:/uimg/"+new Date().getTime()+file.getOriginalFilename();
File newFile=new File(path);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(newFile);
long endTime=System.currentTimeMillis();
System.out.println("方法二的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "index";
}
三、通过流的方式上传文件
/**
* 第三种上传:
* */
/*
* 通过流的方式上传文件
* @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
*/
@RequestMapping("fileUpload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
//用来检测程序运行时间
long startTime=System.currentTimeMillis();
System.out.println("fileName:"+file.getOriginalFilename());
try {
//获取输出流
OutputStream os=new FileOutputStream("E:/uimg/"+new Date().getTime()+file.getOriginalFilename());
//获取输入流 CommonsMultipartFile 中可以直接得到文件的流
InputStream is=file.getInputStream();
int temp;
//一个一个字节的读取并写入
while((temp=is.read())!=(-1))
{
os.write(temp);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endTime=System.currentTimeMillis();
System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "index";
}
四、采用spring提供的上传文件的方法
/*
*采用spring提供的上传文件的方法
*/
@RequestMapping("springUpload")
public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException
{
long startTime=System.currentTimeMillis();
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
//将request变成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
@SuppressWarnings("rawtypes")
Iterator iter=multiRequest.getFileNames();
while(iter.hasNext())
{
//一次遍历所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String path="E:/uimg/"+file.getOriginalFilename();
//上传
file.transferTo(new File(path));
}
}
}
long endTime=System.currentTimeMillis();
System.out.println("方法四的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "index";
}
dome下载地址:https://download.csdn.net/download/qq_40910788/10876637