在SpringMVC中静态资源文件是五法直接被访问的, 需要在SpringMVC的配置文件中配置
所谓的静态资源文件主要指:js、css,img…等等
配置如下:底下的配置意思是代表,WebRoot底下的某个文件夹底下的所有文件
location表示位置
/ 表示该目录底下的所有文件
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/css" mapping="/css/**"/>
添加文件上传的解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242800"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
页面
单文件
<form method="post" action="imgFileUpload" enctype="multipart/form-data">
<input type="file" name="image"> <br/>
<input type="submit" value="上传文件">
</form>
多文件
<form method="post" action="imgsFileUpload" enctype="multipart/form-data">
<input type="file" name="image"> <br/>
<input type="file" name="image"> <br/>
<input type="file" name="image"> <br/>
<input type="submit" value="上传文件">
</form>
[collapse status=“false” title=“Form标签中enctype属性”]
定义和用法
enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
默认地,表单数据会编码为 “application/x-www-form-urlencoded”。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 “+” 加号,特殊符号转换为 ASCII HEX 值)。
语法
<form enctype="value">
属性值
值 | 描述 |
---|---|
application/x-www-form-urlencoded | 在发送前编码所有字符(默认) |
multipart/form-data | 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。 |
text/plain | 空格转换为 “+” 加号,但不对特殊字符编码。 |
[/collapse]
控制器
单文件上传
@RequestMapping(value = "imgFileUpload")
public String imgFileUpload(@RequestParam(value = "image",required = true) MultipartFile image, HttpServletRequest request) throws IOException {
//1.判断是否有文件传来
if(image!=null){
//2.设置上传路径
String path = request.getSession().getServletContext().getRealPath("/") + "/img/";
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();//如果这个路径不存在,则创建该目录
}
//3.转存文件
// getOriginalFilename() 获取文件名
File file = new File(path, image.getOriginalFilename());
//分目录存放, 和文件名的处理, 在SpringMVC中一样需要
image.transferTo(file);
}
return "success";
}
多文件上传
@RequestMapping(value = "imgsFileUpload")
public String imgsFileUpload(@RequestParam(value = "image",required = true) MultipartFile[] images, HttpServletRequest request) throws IOException {
//1.判断文件是否为空
if(images!=null){
//2.设置上传路径
String path = request.getSession().getServletContext().getRealPath("/")+"/img/";
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();//如果这个路径不存在,则创建该目录
}
//3.转存文件
for (MultipartFile img:images) {
File file = new File(path,img.getOriginalFilename());
img.transferTo(file);
}
}
return "success";
}