SpringMVC配置文件上传解析器实现文件上传项目实例
1、在pom.xml文件中添加相关依赖
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2、在springmvc.xml配置文件中配置文件上传解析器
<!--配置文件上传解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242880" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
3、在controller类中编写测试代码
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping(path="/upload")
public String upload(HttpServletRequest request,
MultipartFile upload,Model model) throws IOException {
System.out.println("springmvc方式的文件上传");
String path =
request.getSession().getServletContext().getRealPath("/uploads");
System.out.println("path:"+path);
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
String filename = upload.getOriginalFilename();
upload.transferTo(new File(path,filename));
model.addAttribute("msg", "欢迎你 springmvc");
return "success";
}
}
4、在index.jsp页面设置上传文件代码
<form action="/account/upload" method="post" enctype="multipart/form-data">
文件: <input type="file" name="upload"></input>
<input type="submit" value="提交">
</form>