- 新建web项目
- 导入 jar 包,文件上传需要导入 commons-io, commons-fieupload.
- 配置 web.xml
<!-- springmvc前端控制器配置 --> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
注意:servlet-mapping如果为 / 时,要拦截所要的请求。
- 编写文件上传处理器
@Controller public class FileUploadController { @RequestMapping("/upload") public String fileupload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest req){ String path = req.getRealPath("/upload"); //获取原始文件名 String fileName = file.getOriginalFilename(); try { InputStream is = file.getInputStream(); OutputStream os = new FileOutputStream(new File(path,fileName)); byte[] buffer = new byte[400]; int len=0; while((len=is.read(buffer))!=-1) os.write(buffer, 0, len); os.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "forward:/success.jsp"; } }
- 编写 springmvc配置文件,需要配置MultipartResolver
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 多媒体解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="100000000"/> </bean> <mvc:annotation-driven/> <context:component-scan base-package="cn.wh.controller"/> </beans>
- 编写 jsp 页面
<form action="upload.do" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="file"/><input type="submit" value="上传"/> </form>
请求路径不能和上传的目录一致