springmvc文件上传(很简单哈-.-)

本文详细介绍使用SpringMVC进行文件上传的过程,包括所需依赖、配置步骤及前后台代码实现。通过具体实例帮助读者理解并掌握文件上传的技术要点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring mvc实现文件上传

1、导入jar包(spring核心包等略)

<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-io</artifactId>
		<version>${commons-io.version}</version>
</dependency>

<!-- 文件上传组件 -->
<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>${commons-fileupload.version}</version>
</dependency>

我这里分别用的1.3.2和1.3.1

2、spring-mvc.xml文件中加入配置

    <!-- 多部分文件上传 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 上传最大大小 单位:字节 -->
		<property name="maxUploadSize" value="104857600" />
		<!-- 写到磁盘之前最大大小,超过依然能上传,但是不会存到内存中  -->
		<property name="maxInMemorySize" value="4096" />
		<!-- 编码方式 默认ISO8859-1 -->
		<property name="defaultEncoding" value="UTF-8"></property>
	</bean>

3、后台代码

@RequestMapping("/fileUpload")
	public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IllegalStateException, IOException {
		String path = "E:/" + new Date().getTime() + file.getOriginalFilename();
		File newFile = new File(path);
		// 通过CommonsMultipartFile的方法直接写文件(注意这个时候)
		file.transferTo(newFile);
		return "success";
	}

4、前台代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data">
	<input type="file" name="file"  />
	<input type="submit" /> 
</form>

</body>
</html>

注意method、ectype是固定写法,file的name属性要和后台的@RequestParam("")里面的值要一致

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值