SpringMVC在Servlet3.0下上传文件的示例

下面贴出主要的配置和代码。
html

web.xml
java

<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<multipart-config>
			<max-file-size>5242880</max-file-size><!-- 5MB -->
			<max-request-size>20971520</max-request-size><!-- 20MB -->
			<file-size-threshold>0</file-size-threshold>
		</multipart-config>
	</servlet>

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

在<multipart-config>中,配置相关信息,限制文件上传的大小等。git

相关可配置信息以下:github

  • file-size-threshold:数字类型,当文件大小超过指定的大小后将写入到硬盘上。默认是0,表示全部大小的文件上传后都会做为一个临时文件写入到硬盘上。web

  • location:指定上传文件存放的目录。当咱们指定了location后,咱们在调用Partwrite(String fileName)方法把文件写入到硬盘的时候能够,文件名称能够不用带路径,可是若是fileName带了绝对路径,那将以fileName所带路径为准把文件写入磁盘。spring

  • max-file-size:数值类型,表示单个文件的最大大小。默认为-1,表示不限制。当有单个文件的大小超过了max-file-size指定的值时将抛出IllegalStateException异常。express

  • max-request-size:数值类型,表示一次上传文件的最大大小。默认为-1,表示不限制。当上传时全部文件的大小超过了max-request-size时也将抛出IllegalStateException异常。spring-mvc




SpringMVC的配置文件:mvc

 <context:component-scan base-package="com.github.upload" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
    
<mvc:annotation-driven />

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>


注意在使用Commons FileUpload方式上传的时候,MultipartResolver的实现是app

org.springframework.web.multipart.commons.CommonsMultipartResolver

而在这里,须要将实现配置成

org.springframework.web.multipart.support.StandardServletMultipartResolver




HTML页面以及controller:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
	<form action="fileUpload.do" method="post" enctype="multipart/form-data">
		文件: <input type="file" name="uploadFile" /><br/>
		<input type="submit" value="上传" />
	</form>
</body>
</html>


@Controller
public class FileUploadController {
	
	 private static final Logger log = LogManager.getLogger("FileUpload");
	@ResponseBody
	@RequestMapping("/fileUpload")
	public Object fileUpload(MultipartFile uploadFile) {
		log.info( () -> uploadFile.getOriginalFilename());
		log.info( () -> uploadFile.getSize());
		log.info( () -> uploadFile.getName());
		
		return "hello world!";
	}
}


参考工程的GitHub地址:

https://github.com/ivyboy/spring-example

相关文章
相关标签/搜索