`
sxdtzhaoxinguo
  • 浏览: 214464 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

SpringMVC文件上传

 
阅读更多

一:准备工作:

1.搭建SpringMVC框架:

所需的jar包截图如下:




2.配置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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>springmvc01</display-name>
<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>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>


<!-- spring 统一字符编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- encoding filter for jsp page -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

3.配置spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.0.xsd">

<!-- 注解扫描包 -->
<context:component-scan base-package="com.ydsn.web.controller.*"/>

<!-- 开启注解和下面的开启注解效果一样(这里是注解的优化版本) -->
<mvc:annotation-driven/>

<!-- 上传文件解析器配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>

<!-- 开启注解 -->
<!--
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
-->

<!-- 返回视图解析器配置 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

<!-- 静态资源访问 -->
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>

</beans>

4.编写controller:

package com.ydsn.web.controller.upload;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
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.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


/**
* 文件上传
* @author sunxinggang
*
*/
@Controller
@RequestMapping("/file")
public class UploadController {


/**
* 这个方式上传文件的弊端就是,当文件大的时候就比较慢
* @param file
* @param request
* @param response
* @return
*/
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
System.out.println("fileName---->"+file.getOriginalFilename());
if(!file.isEmpty()){
try {
//输出流
FileOutputStream os = new FileOutputStream("D:/"+new Date().getTime()+file.getOriginalFilename());
//输入流
InputStream is = file.getInputStream();
int b = 0;
//读文件
while((b=is.read())!=-1){
os.write(b);
}
//刷新,关闭流
os.flush();
os.close();
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "/success";
}

/**
* 这中方式的好处就是大文件也上传的很快,一般都采用此种方式上传文件
* @param request
* @param response
* @return
* @throws IllegalStateException
* @throws IOException
*/
@RequestMapping("/upload2")
public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
//定义解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
if(multipartResolver.isMultipart(request)){
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iterator = multiRequest.getFileNames();
while(iterator.hasNext()){
MultipartFile file = multiRequest.getFile((String)iterator.next());
if(file != null){
String fileName = "demoUpload" + file.getOriginalFilename();
String path = "D:/"+fileName;
File localFile = new File(path);
//将上传文件写到服务器上指定的文件
file.transferTo(localFile);
}
}
}
return "/success";
}

@RequestMapping("/toUpload")
public String toUpload(){
return "/upload";
}
}

5.接下来编写jsp也没:

upload.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<div>文件上传</div>
<form name="userForm" action="/springmvc07/file/upload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>

success.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
上传成功!
</body>
</html>

最后项目截图:




结束:访问:http://localhost:8080/springmvc07/file/toUpload就可以了

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics