首先导入jar包
<!--文件上传所需jar包-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
在springMVC配置文件中配置文件解析器对象
<!-- 配置文件解析器对象,要求id名称必须是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"></property>
</bean>
最后写Controller
@RequestMapping("/fileUpload")
public String fileUpload(HttpServletRequest request,MultipartFile upload) throws IOException {
System.out.println("SpringMVC方式上传文件......");
//先获取要上传文件的目录
String path = "C:/Users/lenovo/Desktop/uploads";
File file = new File(path);
System.out.println(file);
//如果路径不存在就创建文件夹
if(!file.exists()){
file.mkdirs();
}
String fileName = UUID.randomUUID().toString().replaceAll("-","")+"_"+upload.getOriginalFilename();
System.out.println(fileName);
//完成文件上传
upload.transferTo(new File(path,fileName));
return "success";
}