springMVC上传文件的两种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010741376/article/details/44814569

web.xml文件:

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
	
	  <servlet>
  	<servlet-name>springMVC</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  		<init-param>
  			<param-name>contextConfigLocation</param-name>
  			<param-value>/WEB-INF/springMVC-servlet.xml</param-value>
  		</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
	
	  <servlet-mapping>
  	<servlet-name>springMVC</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
	
	
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

springmvc配置文件:

 

<?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.springmvc.controller"></context:component-scan>
      <mvc:annotation-driven/>
      
      
      
      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	       <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	       <property name="defaultEncoding" value="utf-8" />
	       <property name="maxUploadSize" value="10485760000" />
	      <property name="maxInMemorySize" value="40960" />
	</bean>
      
      </beans>

Controller控制器(有两种方式上传文件)

<span style="font-size:14px;">package com.springmvc.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.http.HttpRequest;
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
public class UploadController {
    
	@RequestMapping("/toUpload.do")
	public String toUpload(){
		return "/upload";
	}
	
	/**
	 * 第一种方式,通过流上传文件
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/upload.do")
	public String addFile(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
		System.out.println("fileName-->"+file.getOriginalFilename());
		if(!file.isEmpty()){
			try {
				FileOutputStream os=new FileOutputStream("F:/"+new Date().getTime()+file.getOriginalFilename());
			    InputStream in=file.getInputStream();
				int b=0;
				byte[] buffer=new byte[1024];
			    while((b=in.read(buffer))!=-1){
			    	os.write(buffer, 0,b);
			    }
			    os.flush();
			    os.close();
			    in.close();
			
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
	
		}
		return "/success";	
	}
	
	
	/**
	 * 第二种方式,通过springMVC自己的文件上传解析器上传文件,效率比第一种更快
	 * @param request
	 * @param response
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping("/upload2.do")
	public String addFile2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		CommonsMultipartResolver multipart=new CommonsMultipartResolver(request.getSession().getServletContext());
		if(multipart.isMultipart(request)){
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
		   Iterator<String> iter=multiRequest.getFileNames();
			while(iter.hasNext()){
			  MultipartFile file=multiRequest.getFile((String)iter.next());
			  if(file!=null){
				  String fileName="UploadFile"+file.getOriginalFilename();
				  String path="D:/"+fileName;
				  File localFile=new File(path);
				  file.transferTo(localFile);
			  }
			  
			  
			}
			
			
			
			
		}
		
		
		
		return "/success";
	}
	
}</span>

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 'upload.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="myform" action="upload2.do" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="file"/>
    <input type="submit" value="上传"/>
     </form>
  </body>
</html>

成功后:

<%@ 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 'success.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>
   上传成功!
  </body>
</html>



上一篇:linux vim中设置tab和空格等同


下一篇:Spring MVC 中的 forward 和 redirect