文件上传
文件上传需要使用以下两个依赖包(同样需要引入到项目依赖中):
commons-fileupload-1.3.3.jarcommons-io-2.6.jar
servlet.xml 配置
在 servlet.xml 中配置文件上传解析器及最大上传大小:
<!-- upload settings -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="102400000"></property>
</bean>Code language: HTML, XML (xml)
控制器方法
增加一个 upload 方法来处理上传:
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest req) throws Exception{
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
MultipartFile file = mreq.getFile("file");
String fileName = file.getOriginalFilename();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String path = req.getSession().getServletContext().getRealPath("/") + "upload/";
File file1 = new File(path);
if(!file1.exists())
{
Boolean aa = file1.mkdir(); // true
}
System.out.println(path);
FileOutputStream fos = new FileOutputStream(path + sdf.format(new Date()) + fileName.substring(fileName.lastIndexOf('.')));
fos.write(file.getBytes());
fos.flush();
fos.close();
return "hello";
}
@RequestMapping("/upload")
public String upload(){
return "upload";
}Code language: JavaScript (javascript)
上传视图(upload.jsp)
<%@ 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>Insert title here</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="submit">
</form>
</body>
</html>Code language: HTML, XML (xml)
Previous: 使用 Jackson 实现 JSON 序列化返回