springMVC文件上传优化

1. 新建web project

2. 填 jar,注意新加入两个上传文件的jar, commons-io, commons-fileupload

3. 改写web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.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>

  <filter>
        <filter-name>characterEncodingFilter</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>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <servlet-mapping>
  	<servlet-name>springMVC</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

4. 新增config包, 新建spring-servlet.xml

新增了上传文件需要的bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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-3.0.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 注解扫描包 -->
    <context:component-scan base-package="com.tgb.web.controller" />      

    <!-- 开启注解 -->
    <mvc:annotation-driven/>

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

    <!-- ViewResolver 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 上传文件 -->
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="defaultEncoding"  value="UTF-8"/>
          <property name="maxUploadSize"    value="1048576000"/>
          <property name="maxInMemorySize"  value="40960"/>
    </bean> 

</beans>

5. 写controller方法, uploadController.java

package com.tgb.web.controller;

import java.io.File;
import java.io.FileNotFoundException;
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;

@Controller
@RequestMapping("/file")
public class UploadController {
	@RequestMapping("/upload")
	public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
		System.out.println("filename--->"+file.getOriginalFilename());
		if(!file.isEmpty()){
			try {
				FileOutputStream os = new FileOutputStream("D:/"+new Date().getTime()+file.getOriginalFilename());
				InputStream in =  file.getInputStream();
				int b = 0;
				while((b=in.read())!=-1){
					os.write(b);
				}
				os.flush();
				os.close();
				in.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "/success";
	}

	@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> iter = multiRequest.getFileNames();
			if(iter.hasNext()){
				MultipartFile file = multiRequest.getFile((String)iter.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";
	}
}

  

6. 写jsp文件, upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
    <title>My JSP ‘upload.jsp‘ starting page</title>
  </head>
  <body>
	  <h> 添加用户 </h> <br>
	  <form name="fileForm" action="/springMVCUpload/file/upload2" method="post" enctype="multipart/form-data">
	  	选择文件: <input type="file" name="file">
	  	<input type="submit" value="上传">
	  </form>

  </body>
</html>

还有succuss.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
    <title></title>
  </head>
  <body>
	  上传文件成功
  </body>
</html>

  

7. 地址栏验证

http://localhost:8080/springMVCUpload/file/toUpload

  

  

 

时间: 2024-11-07 01:03:42

springMVC文件上传优化的相关文章

springMVC3学习(十二)--文件上传优化CommonsMultipartResolver

基于上一篇文件上传发现效率很慢,我们应该对它进行优化  使用springMVC对文件上传的解析器 来处理文件上传的时候需要在spring的applicationContext里面加上springMVC提供的MultipartResolver的申明 这样客户端请求的时候 springMVC会检查request里面是否包含多媒体信息 如果包含了就会使用MultipartResolver进行解析, springMVC会使用一个支持文件  处理的MultipartHttpServletRequest来包

eclipse中导入jdk源码、SpringMVC注解@RequestParam、SpringMVC文件上传源码解析、ajax上传excel文件

eclipse中导入jdk源码:http://blog.csdn.net/evolly/article/details/18403321, http://www.codingwhy.com/view/799.html. ------------------------------- SpringMVC注解@RequestParam:http://825635381.iteye.com/blog/2196911. --------------------------- SpringMVC文件上传源

关于使用 Connect-Busboy 实现文件上传 优化说明

这篇博文完全上关于上一篇的优化 先看上一篇 node.js 在 Express4.0 框架使用 Connect-Busboy 实现文件上传 因为从上次博客改用 connect-busboy 来上传文件后,发现了明显的一个bug bug 说明 文件显示上传 100% ,然后预览的时候,偶尔会发现图片只能显示一部分 这种情况在 png 格式 图片尤其严重 昨天重新 review 代码,发现一个bug ,当然和 connect-busboy 一点关系都没有,而是涉及到流的处理过程. 这里把上一篇 bl

springmvc文件上传2中方法

基于前面文章的基础上. 一.准备 需要的jar  二.配置 1.  spmvc-servlet.xml <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x

springmvc文件上传及表单数据封装

补充: form表单需要提交时间,springmvc封装到实体类的Date字段时,丢失时分秒,可以在controller中添加     @InitBinder     public void initBinder(WebDataBinder binder) {         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         dateFormat.setLenient(f

SpringMVC文件上传——bean的配置【org.springframework.web.multipart.commons.CommonsMultipartResolver】

一.简介 Spring MVC支持一个通用的多路上传解析器CommonsMultipartResolver,在Spring的配置文件中对CommonsMultipartResolver Bean进行配置时,有一些可选的属性配置. 二.分析 经过百度和查看SpringMVC的API文档都没有发现相关的详细配置介绍,无可奈何只能查看源代码寻找蛛丝马迹: 在Spring配置文件applicationContext.xml中配置了CommonsMultipartResolver Bean后,按 " Ct

springmvc文件上传AND jwt身份验证

SpringMVC文件上传 思路:1.首先定义页面,定义多功能表单(enctype=“multipart/form-data”)2.在Controller里面定义一个方法,用参数(MultipartFile)来接收前台传递过来的文件对象3.然后文件上传就是把文件从一个地方(本地)复制到另外一个地方(服务器) 添加pom依赖 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commo

Springmvc文件上传

1.commons-fileupload-1.2.2.jar 2.commons-io-2.0.1.jar 2.要实现SpringMVC的文件上传,需要配置一下文件: 1 <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 2 <bean id="multipartResolver" 3 class="org.springframework.web.multipart.commons.CommonsMultipa

SpringMVC文件上传实现

SpringMVC(注解)上传文件需要注意的几个地方:1.form的enctype="multipart/form-data",这个是上传文件必须的2.applicationContext.xml配置: <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.