springmvc文件的上传

一. 文件的上传

  1. maven导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.1.3.RELEASE</version>
</dependency>

  1. spring.xml配置上传文件组件
 <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" />
        <!-- 生成临时文件大小限制,0为不受大小限制 -->
        <property name="fileItemFactory.sizeThreshold" value="0"/>
    </bean>

当收到请求后,DispatcherServlet的checkMultipart()方法会调用MultipartResolver中的isMultipart(request)方法判断请求中是否包含文件,如果请求数据中包含文件,则调用 MultipartResolver 的 resolveMultipart() 方法对请求的数据进行解析,然后将文件数据解析成 MultipartFile 并封装在 MultipartHttpServletRequest (继承了 HttpServletRequest) 对象中,最后传递给 Controller。
3. Controller层代码uploadFileController.java

@Controller
public class uploadFileController{
	@RequestMapping("/uploadFile.action")
	public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest req){
		try{
			//判断文件是否为空
			if(!file.isEmpty()){
				//获取上传文件的本地绝对路径
				String path = req.getServletContext().getRealPath("/");
				//创建目标文件的File对象
				File uploadFile = new File(path, file);
				//执行文件的上传操作,将文件存储到指定位置
				file.transferTo(File);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
  1. 前端页面
    注意将form表单的enctype属性设置为multipart/form-data
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值