简要的代码罗列
1、需要的jar包
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2、dispatcher-servlet.xml
<!--需要添加bean-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
3、Controller
@RequestMapping(value="/doUpload",method=RequestMethod.POST)
public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException{
if(!file.isEmpty()){
FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E:\\temp\\",System.currentTimeMillis()+file.getOriginalFilename()));
}
return "success";
}
5、upload.jsp
<form action="<%=request.getContextPath()%>/hello/doUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
注意: jsp文件中enctype属性需要写,不然会报以下的错
这里的坑我查了很久,需要很注意!!!!