本例演示使用在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>