springMVC上传文件的两种方式

简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.
版权声明:本文为博主原创文章,未经博主允许不得转载。 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>



相关文章
|
C++
C/C++给文件加crc校验
C/C++给文件加crc校验
256 1
|
10月前
|
UED 开发者
鸿蒙next版开发:ArkTS组件通用属性(图片边框设置)
在HarmonyOS 5.0中,ArkTS提供了灵活的图片边框设置属性,使开发者可以为应用中的图片组件添加各种边框效果,提升视觉效果和用户体验。本文详细解读了ArkTS中图片边框设置的通用属性,并提供了示例代码。通过设置`borderImage`属性,可以控制边框的图源、切割宽度、边框宽度、延伸距离、平铺模式和是否填充。示例代码展示了如何使用这些属性来创建具有不同边框效果的图片组件。图片边框设置在美化界面、区分内容和增强交互方面有重要作用。
432 5
|
10月前
|
算法 Java API
Sentinel学习圣经:从入门到精通 Sentinel,最全详解 (40+图文全面总结)
尼恩给大家做一下系统化、体系化的梳理,联合社群小伙伴,来一个Sentinel学习圣经:从入门到精通Sentinel。
|
存储 缓存 负载均衡
高可用分布式缓存:深入了解 Redis Cluster
在现代的分布式系统中,高效的缓存方案对于提高性能和可扩展性至关重要。Redis Cluster,作为一种分布式的高可用缓存解决方案,能够满足大规模应用的缓存需求。本文将为您详细介绍 Redis Cluster 的核心概念、特性以及在分布式架构中的应用。
538 0
|
XML 机器学习/深度学习 数据格式
YOLOv8训练自己的数据集+常用传参说明
YOLOv8训练自己的数据集+常用传参说明
19607 1
|
监控 算法 测试技术
【Go语言专栏】Go语言的性能优化与内存分析
【4月更文挑战第30天】本文探讨了Go语言的性能优化策略和内存分析方法。性能优化原则包括基准测试、分析瓶颈、避免过早优化和持续监控。优化策略涉及减少内存分配、避免内存逃逸、利用并发、优化算法和数据结构以及减少系统调用。内存分析借助于Go的`pprof`工具、内存分配跟踪和第三方工具,以发现内存泄漏和管理问题。通过这些方法,开发者能提升Go程序效率和资源利用率。
205 0
|
存储 缓存 Unix
QEMU-img工具
QEMU-img工具
1979 1
|
SQL 存储 人工智能
|
Shell
Shell 输入/输出的重定向含义(>、>>、2>、2>>、&>、&>>、1>&2、2>&1)
Shell 输入/输出的重定向含义(>、>>、2>、2>>、&>、&>>、1>&2、2>&1)
244 0