1、文件上传
1.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.4</version>
</dependency>
1.2 设置文件上传解析器
bean的名字是固定的:multipartResolver
<!--配置文件上传解析器 id必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置文件大小的上限 1Mb-->
<property name="maxUploadSize" value="#{1024*1024}"/>
</bean>
1.3 jsp页面
<fieldset>
<legend>文件上传</legend>
<%--必须设置 表单的提交类型:"multipart/form-data"--%>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="提交">
</form>
</fieldset>
1.4 新建文件上传的Controller类
@Controller
public class UploadFile {
/*文件上传*/
@Autowired
private ServletContext servletContext;
@RequestMapping("/upload")
public ModelAndView file(String filename, MultipartFile file) throws Exception{
/*把文件对象以流形式,写入到目标文件夹中(只能保存到target文件夹中)*/
String realPath = servletContext.getRealPath("/");
/*自定义保存文件的文件名*/
String path = realPath + new Date().getTime() + file.getOriginalFilename();
/*加载*/
File newfile = new File(path);
/*执行*/
file.transferTo(newfile);
return null;
}
}
2、文件下载
2.1 jsp页面
<fieldset>
<legend>文件下载</legend>
<form action="/download" method="post">
输入要下载的文件名<input name="filename"/><br/>
<input type="submit" value="提交">
</form>
</fieldset>
2.2 新建文件下载的Controller类
@Controller
public class DownloadFile {
/*文件下载*/
@Autowired
private ServletContext context;
@RequestMapping("/download")
public ModelAndView download(String filename, HttpServletResponse response) throws Exception{
/*设置文件下载的响应头*/
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition","attachment;filename="+filename);
//设置图片所在路径
String realpath = context.getRealPath("/");
//执行
Files.copy(Paths.get(realpath,filename),response.getOutputStream());
return null;
}
}
3、注意:
1.SpringMVC上传必须配置文件上传解析器"org.springframework.web.multipart.commons.CommonsMultipartResolver",解析器的id必须为"multipartResolver"
2.做文件上传的form表单的提交方式必须为"post",同时表单的提交类型为:“multipart/form-data”
3.控制器的方法可以使用MultipartFile对象,接收上传的文件
4.SpringMVC没有对文件的下载做封装