SpringMVC完成文件上传的基本步骤


1、修改form表单的提交方式

2、将文件存入磁盘

3、配置视图解析器

1).前端文件

  --需要在form表单中添加 enctype="multipart/form-data"属性。这是必须要的。

 

2).在SpringMVC核心配置文件中配置文件上传解析器

1 <!--配置文件上传解析器
2     id的名称必须为:multipartResolver
3 -->
4 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
6     <property name="maxUploadSize" value="10485760"></property>
7 </bean>

3).编写Controller核心代码:

 1 @RequestMapping("addUser.action")
 2 public String addUser(@RequestParam("upfile")MultipartFile file,Model model) throws IOException{
 3     //方法一:阿帕奇的对象
 4     FileUtils.writeByteArrayToFile(new File("D:\\"+file.getOriginalFilename()), file.getBytes());
 5    //方法二:MultipartFile 的对象
 6  //uploadFile.transferTo(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\"+uploadFile.getOriginalFilename()));
 7   
 8     model.addAttribute("filemsg", "文件已上传到服务器D盘!");
 9     
10     return "result";  //返回要显示的页面名称,在视图解析器中需要拼接路径
11     
12 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM