Spring MVC 文件上传下载以及静态资源处理
一、文件的上传
1、引入相关jar包
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190422190506366.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xPWUVfWU9V,size_16,color_FFFFFF,t_70)
2、前端jsp页面
<form method="post" action="upload" enctype="multipart/form-data">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>上传文件:</td>
<td><input type="file" name="file"></td>
</tr>
<tr>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
3、访问页面
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190422190847755.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xPWUVfWU9V,size_16,color_FFFFFF,t_70)
4、controller接收数据
@RequestMapping("/upload")
@ResponseBody
public void upload(String name,MultipartFile file) throws Exception {
file.transferTo(new File("d:/111.jar"));
System.out.println(name + " " + file.getOriginalFilename());
}
5、配置xml文件
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="maxUploadSize" value="5242880"/>
</bean>
二、文件下载
1、controller基于ResponseEntity实现
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpServletRequest request)throws IOException{
File file = new File("d://cglib-nodep-3.1.jar");
byte[] by = null;
InputStream is = new FileInputStream(file);
by = new byte[is.available()];
is.read(by);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(by, headers, status);
return entity;
}
2、前端jsp页面
<a href="download">文件下载</a>
3、访问页面
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190422192117538.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xPWUVfWU9V,size_16,color_FFFFFF,t_70)
三、静态资源过滤处理
方式一:在web.xml中配置default servlet
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
方式二:在Spring MVC 配置文件中配置
1、方式一:
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
2、方式二:
<mvc:resources location="/" mapping="/**"/>