在文件上传时,我们需要用到文件上传解析器,其实,它并不陌生,只是对httpServletRequest的一个扩展,使其能够更好的处理文件上传,扩展的接口名为:org.springframework.web.multipart.MultipartHttpServletRequest
先用一个类图看一下这个它的底层架构:
下面用代码层面看一下如何实现:
1、web.xml中配置
<bean id="multipartResolver"
class="<span style="color:#ff0000;">org.springframework.web.multipart.commons.CommonsMultipartResolver</span>">
<!-- 文件最大值 -->
<property name="maxUploadSize" value="1048576000" />
<property name="defaultEncoding" value="utf-8"/>
<!-- 缓存大小 -->
<property name="maxInMemorySize" value="40960"></property>
</bean>
2、Controller中实现文件的上传
@Controller
@RequestMapping("/file")
public class UploadController {
@RequestMapping(value="/upload")
public String addUser(@RequestParam("<span style="color:#ff0000;"><strong>file</strong></span>")CommonsMultipartFile file,HttpServletRequest request) throws IOException{
System.out.println("fileName--->"+file.getOriginalFilename());
if (!file.isEmpty()) {
try {
//定义文件的路径
FileOutputStream os=new FileOutputStream("D:/"+new Date().getTime() +file.getOriginalFilename());
//上传文件
InputStream in=file.getInputStream();
int b=0;
//如果文件内容部位空
while ((b=in.read())!=-1){
os.write(b);
}
os.flush();//刷新
os.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "/success";
}
3、jsp中拼出页面
注意:两处加红的字体必须一致
<form name="userForm" action="/ springMVC7/file/upload" method="post" enctype="multipart/form-data">
选择文件:<input type="text" name="<span style="color:#ff0000;"><strong>file</strong></span>">
<input type="submit" value="上传" οnclick="addUser()">
</form>