6.SpringMVC的文件上传
6.1-SpringMVC的请求-文件上传-客户端表单实现(应用)
文件上传客户端表单需要满足:
-
表单项type=“file”
-
表单的提交方式是post
-
表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”
<form action="${pageContext.request.contextPath}/user/login22" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件1<input type="file" name="uploadFile"><br/>
<input type="submit" value="提交">
</form>
6.2-SpringMVC的请求-文件上传-文件上传的原理(理解)
6.3-SpringMVC的请求-文件上传-单文件上传的代码实现1(应用)
添加依赖
<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.3</version>
</dependency>
配置多媒体解析器
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UYF-8"/>
<property name="maxUploadSize" value="500000"/>
</bean>
后台程序
@RequestMapping(value="/login22")
@ResponseBody
public void login22(String username, MultipartFile uploadFile) throws IOException {
System.out.println(username);
System.out.println(uploadFile);
}
6.4-SpringMVC的请求-文件上传-单文件上传的代码实现2(应用)
完成文件上传
@RequestMapping(value="/quick22")
@ResponseBody
public void login22(String username, MultipartFile uploadFile) throws IOException {
System.out.println(username);
//获得上传文件的名称
String originalFilename = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("D:\\upload\\"+originalFilename));
}
6.5-SpringMVC的请求-文件上传-多文件上传的代码实现(应用)
多文件上传,只需要将页面修改为多个文件上传项,将方法参数MultipartFile类型修改为MultipartFile[]即可
<form action="${pageContext.request.contextPath}/user/quick23" method="post" enctype="multipart/form-data">
名称<input type="text" name="username"><br/>
文件1<input type="file" name="uploadFile"><br/>
文件2<input type="file" name="uploadFile"><br/>
<input type="submit" value="提交">
</form>
@RequestMapping(value="/login23")
@ResponseBody
public void save23(String username, MultipartFile[] uploadFile) throws IOException {
System.out.println(username);
/*
//MultipartFile uploadFile, MultipartFile uploadFile2
String filename1 = uploadFile.getOriginalFilename();
uploadFile.transferTo(new File("D:\\uploadFile\\" + filename1));
String filename2 = uploadFile2.getOriginalFilename();
uploadFile2.transferTo(new File("D:\\uploadFile\\" + filename2));
*/
for (MultipartFile multipartFile : uploadFile) {
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("D:\\upload\\"+originalFilename));
}
}
6.6-SpringMVC的请求-知识要点(理解,记忆)
在进行文件上传时需要前台的file的名称与后台的名称一致,才能进行文件上床。