Springmvc文件上传

  1. 导入jar包(springmvc项目用到的jar+spring依赖包中apache的两个文件上传的jar)springmvc文件上传
  2. 修改form表单中的属性为:enctype="multipart/form-data"
  3. 在springmvc的配置文件中配置多媒体文件解析器实现上传springmvc文件上传
  4. 创建保存上传文件的文件夹:E:\13 SpringMVC\upload
  5. 配置虚拟目录与物理目录的映射
  6. springmvc文件上传
  7. 切换为Moduels,添加
  8. springmvc文件上传
  9. 物理目录与虚拟目录映射

  10. springmvc文件上传

  11. 映射之后,将项目publish到tomcat中,可以在tomacat文件的conf----server.xml文件中看到该映射已经被加载到tomcat中
  12. springmvc文件上传

  13. 配置资源文件,将保存路径作为参数写在资源文件中(savePath=E:\\13 SpringMVC\\upload\\)资源文件名是resource.properties,特别注意:保存路径写完物理路径后再加上\\,这样才能直接拼接文件名。写完配置文件之后,在springmcv.xml中引入资源文件。

  14. <!-- 引入resource.properties文件 -->

  15. <context:property-placeholder location="classpath:resource.properties"/>

  16. 在处理器中创建上传文件的方法

  17.  

    springmvc文件上传

    //获取所有商品信息
        @RequestMapping("/items/list.action")
        public String getAllItems(Model model){//处理器提供的默认形参
            List<Items> list = itemsService.getAllItems();
            //将items放入request中
            model.addAttribute("items",list);
            //返回视图,在springmvc.xml中配置了前缀和后缀将返回的字符串与前缀和后缀拼接,就是要返回的视图
            return "itemsList";
        }

     

    //测试文件上传,需要在该方法中添加一个参数(MultipartFile pictureFile),这个参数名要和页面中的多媒体的name值一样
        @RequestMapping(value="/items/edit.action",method={RequestMethod.GET,RequestMethod.POST})//注解中可以设置能够接受的参数提交方式有哪些
        public String editItems(Items it,Model m,MultipartFile pictureFile) throws Exception{
            //调用文件上传的方法
                String string = uploadFile(pictureFile);//如果上传了文件,返回的是文件名,如果没有上传文件,返回的是null
                if(string != null){
                    //返回值不为空,说明有文件上传
                    it.setPic(string);//将文件名保存到Items中
                }
                m.addAttribute("item", it);
                itemsService.editItems(it);
                return "redirect:/items/list.action";//重定向到列表处理器,如果是转发,就把redirect改为forward
        
        }
        

相关文章: