SpringMVC入门 (六) 文件上传

1.单个文件上传

在Controller的add方法中加入:
@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(@Validated User user, BindingResult result, MultipartFile attach){   
		
		String realpath=req.getSession().getServletContext().getRealPath("/resources/upload");
		File f=new File(realpath+"/"+attach.getOriginalFilename());
		try {
			FileUtils.copyInputStreamToFile(attach.getInputStream(),f );
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		users.put(user.getUsername(), user);
		return "redirect:/user/users";  
	}


这里的MultipartFile就包含了上传文件的内容信息。

在add.jsp页面中加入文件上传:
  <body>
   	
   	<sf:form method="post" modelAttribute="user" enctype="multipart/form-data">
   		用户名称:<sf:input path="username"/><sf:errors path="username"/><br/>
   		用户密码: <sf:input path="password"/><sf:errors path="password"/><br/>
   		用户昵称: <sf:input path="nickname"/> <br/>
   		用户邮箱: <sf:input path="email"/><sf:errors path="email"/><br/>
   		附件:<input type="file" name="attach"/><br/>
   		 <input type="submit" value="添加用户"/>
   	</sf:form>
   	
  </body>


这里直接上传文件会报错:
Expected MultipartHttpServletRequest: is a MultipartResolver configured?

因此我们需要在hello-servlet.xml中配置这个文件解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>


这里还没完, 打开CommonsMultipartResolver,可以看到

/**
	 * Initialize the underlying {@code org.apache.commons.fileupload.servlet.ServletFileUpload}
	 * instance. Can be overridden to use a custom subclass, e.g. for testing purposes.
	 * @param fileItemFactory the Commons FileItemFactory to use
	 * @return the new ServletFileUpload instance
	 */
	@Override
	protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
		return new ServletFileUpload(fileItemFactory);
	}

这里引用了commons-fileupload里面的类,因此我们还要导入commons-fileupload
<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>	






2.多个文件上传
多文件上传的时候,首先要在add.jsp中加入多个file。
注意这里把attach改成了attachs
  <body>
   	
   	<sf:form method="post" modelAttribute="user" enctype="multipart/form-data">
   		用户名称:<sf:input path="username"/><sf:errors path="username"/><br/>
   		用户密码: <sf:input path="password"/><sf:errors path="password"/><br/>
   		用户昵称: <sf:input path="nickname"/> <br/>
   		用户邮箱: <sf:input path="email"/><sf:errors path="email"/><br/>
   		附件:<input type="file" name="attachs"/><br/>
   		附件:<input type="file" name="attachs"/><br/>
   		附件:<input type="file" name="attachs"/><br/>
   		 <input type="submit" value="添加用户"/>
   	</sf:form>
   	
  </body>

接下来修改Controller里的add方法:
@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(@Validated User user, BindingResult result,
			@RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) { 
		for (MultipartFile attach : attachs) {
			String realpath = req.getSession().getServletContext()
					.getRealPath("/resources/upload");
			File f = new File(realpath + "/" + attach.getOriginalFilename());
			try {
				FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		users.put(user.getUsername(), user);
		return "redirect:/user/users"; 
	}

这里做了两个改动,一个是把MultipartFile attach改成了
MultipartFile[] attachs,
另一个是在前面加入了 @RequestParam("attachs");这个注释可以将前台的parameter的名称和这里的参数捆绑起来:
    
  /**
	 * The name of the request parameter to bind to.
	 */
	String value() default "";)

你可能感兴趣的:(文件上传,springMVC)