1. 文件上传三要素
- 表单项type="file"
- 表单的提交方式是post
- 表单的enctype属性是多部分的表单形式,及enctype="multipat/form-data"
<form action="${pageContext.request.contextPath}/user/quick22" method="post" enctype="multipart/form-data">
文件<input type="file" name="upload"><br/>
<input type="submit">
</form>
2.文件上传原理
- 当form表单修改为多部分表单时,request.getParameter()将失效
- enctype="application/x-www-form-urlencoded"时,form表单的正文内容格式是:
key=value&key=value&key=value - 当form表单的enctype取值为Mutilpart/form-data时,请求正文内容就变成多部分形式
3.文件上传步骤
- 在pom.xml中导入fileupload和io坐标
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242800"></property>
<property name="maxUploadSizePerFile" value="5242800"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
@RequestMapping(value = "/quick22")
@ResponseBody
public void save22(MultipartFile uploadFile,HttpSession session) {
String originalFilename = uploadFile.getOriginalFilename();
String path = session.getServletContext().getRealPath("/upload");
File file = new File(path,originalFilename);
if (!file.exists()) {
file.mkdirs();
}
try {
uploadFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/quick23")
@ResponseBody
public void save23(MultipartFile[] uploadFile,HttpSession session) {
String path = session.getServletContext().getRealPath("/upload/");
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
for (MultipartFile multipartFile : uploadFile) {
String originalFilename = multipartFile.getOriginalFilename();
try {
multipartFile.transferTo(new File(path,originalFilename));
} catch (IOException e) {
e.printStackTrace();
}
}
}