文件的上传与下载基本上是web项目中会用到的技术,在web学习中我们用到的是 Apache fileupload这个组件来实现上传,在springmvc中对它进行了封装,让我们使用起来比较方便,但是底层还是由Apache fileupload来实现的。springmvc中由MultipartFile接口来实现文件上传
一、导包
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
二、编写springmvc.xml配置文件
在springmvc配置文件中配置上传解析器
<!--
id属性是bean的实例名,可以指定
class属性固定不变
property name="maxUploadSize",property name="defaultEncoding",名字固定,值可以指定
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件的最大值,单位为字节 -->
<property name="maxUploadSize" value="20971520"/>
<!-- 上传流的编码 -->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
三、编写前端上传文件的代码
- input的type设置为file
- form表单的method设为post,
- form表单的enctype设置为multipart/form-data,以二进制的形式传输数据。
<form action="testFileUpload" method="POST" enctype="multipart/form-data">
File: <input type="file" name="file"/>
Desc: <input type="text" name="desc"/>
<input type="submit" value="Submit"/>
</form>
四、编写Controller代码
使用MultipartFile对象作为参数,接收前端发送过来的文件,将文件写入本地文件中,就完成了上传操作
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
throws IllegalStateException, IOException {
// 判断文件是否为空,空则返回失败页面
if (file.isEmpty()) {
return "failed";
}
// 获取文件存储路径(绝对路径)
String path = req.getServletContext().getRealPath("/WEB-INF/file");
// 获取原文件名
String fileName = file.getOriginalFilename();
// 创建文件实例
File filePath = new File(path, fileName);
// 如果文件目录不存在,创建目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
System.out.println("创建目录" + filePath);
}
// 写入文件
file.transferTo(filePath);
return "success";
}