springmvc-普通form表单提交方式实现文件上传

本例演示使用在springmvc框架中如何上传文件

1.jsp页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>
<!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>Insert title here</title>
</head>
<body>
	<form action="upload.do" method="post" enctype="multipart/form-data">
		<input type="file" name="imageUpload"/> 
		<input type="submit"/>
	</form>
</body>
</html>

2.后台springmvc控制器的java代码

获取请求并强制转换成MultipartHttpServletRequest的对象mreq,mreq.getFile("xxxx")中xxx要和jsp页面中表单元素name的值相对应,然后通过文件输出流写到相应的文件路径下,并跳转页面

package com.hwua.controler;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class UploadController {

	@RequestMapping("/upload")
	public String upload(HttpServletRequest req) throws IOException {
		MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
		MultipartFile file = mreq.getFile("imageUpload");
		String fileName = file.getOriginalFilename();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/") + "image/"
				+ sdf.format(new Date()) + fileName.substring(fileName.lastIndexOf('.')));
		fos.write(file.getBytes());
		fos.flush();
		fos.close();

		return "/success.jsp";
	}
}

3.applicationContext.xml用到的配置

这个配置没有写的话,在controller中做MultipartHttpServletRequest的强制类型转换时被抛出类转换异常
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize">
			<value>102400000</value>
		</property>
		<property name="maxInMemorySize">
			<value>4096</value>
		</property>
	</bean>

tip:除了springmvc的核心包外,需要添加另外两个jar包


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值