导入pom.xml
<!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>之前在springmvc的配置文件中的视图解析器只能处理常规的方法,需要文件上传需要添加一下配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 文件最大大小(字节) 1024*1024*50=50M--> <property name="maxUploadSize" value="52428800"></property> <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常--> <property name="resolveLazily" value="true"/> </bean>upload.jsp
<%-- Created by IntelliJ IDEA. User: Hasee Date: 2019/11/1 Time: 0:40 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>springmvc文件上传</title> </head> <body> <form action="/book/upload" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="lk" /> <input type="submit" value="上传"> </form> </body> </html>上传方法:
/** * 文件上传 * @param req * @param lk * @return */ @RequestMapping("/upload") public String upload(HttpServletRequest req, MultipartFile lk) { String fileName=lk.getOriginalFilename(); String contenType=lk.getContentType(); try { FileUtils.copyInputStreamToFile(lk.getInputStream(),new File("E:/tup/"+fileName)); } catch (IOException e) { e.printStackTrace(); } return "redirect:/book/list"; }