#文件上传 #SpringMVC文件上传 @FDDLC

    科技2022-08-09  135

    先修课:#文件上传 #commons-fileupload @FDDLC

     

    表单核心部分:

    <form method="post" enctype="multipart/form-data" action="test"> 请选择文件:<input type="file" name="multipartFile"/><br/> <input type="submit" value="提交"/> </form>

    说明:

    1、method="post" enctype="multipart/form-data" 不能改!

    2、<input type="file" name="multipartFile"/> 和 public String test(MultipartFile multipartFile, HttpServletRequest request)的名字得一样!即表单文件域的name值和请求方法的MultipartFile名字得一样!

     

    文件上传的核心代码:

    public String test(MultipartFile multipartFile, HttpServletRequest request) throws IOException { String path = request.getSession().getServletContext().getRealPath("/upload/"); File dir = new File(path); if(!dir.exists()) { dir.mkdirs(); } String uuid = UUID.randomUUID().toString().replace("-", ""); String filename = uuid + multipartFile.getOriginalFilename(); multipartFile.transferTo(new File(path, filename)); System.out.println("找不着上传的文件?在这呢:" + path); return "success"; }

    说明:

    1、不是必须的(servlet-api这个Maven依赖同理),它的作用只是为了获取一个路径。你完全可以直接指定一个存放上传文件的本地路径!比如:

    public String test(MultipartFile multipartFile) throws IOException { multipartFile.transferTo(new File("D:/upload/", multipartFile.getOriginalFilename())); //前提是"D:/upload/"得存在! return "success"; }

    2、再次强调:<input type="file" name="multipartFile"/> 和 public String test(MultipartFile multipartFile, HttpServletRequest request)的名字得一样!即表单文件域的name值和请求方法的MultipartFile名字得一样!请求参数绑定嘛!如果不一样,请用@RequestParam!

    3、需要额外导入commons-fileupload包(servlet-api包可选)

    4、需要在SpringMVC的配置文件中注册文件解析器(id不可自定义!):

    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"

    最后附上源码:

     

    项目结构:

     

    pom.xml的内容:

    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>P057_FileUpload_SpringMVC</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>P057_FileUpload_SpringMVC Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.8.RELEASE</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>servlet-api</artifactId> <version>6.0.36</version> </dependency> </dependencies> <build> <finalName>P057_FileUpload_SpringMVC</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>

     

    web.xml的内容:

    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--关联springmvc.xml,让其中的配置生效!--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

     

    springmvc.xml的内容:

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--开启对Spring MVC注解的支持--> <mvc:component-scan base-package="cn.liuxingchang.controller"></mvc:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--配置对上传文件进行解析的文件解析器--> <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <property name="maxUploadSize" value="10485760"></property><!--以字节为单位--> </bean> </beans>

     

    index.jsp的内容:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <form method="post" enctype="multipart/form-data" action="test"> 请选择文件:<input type="file" name="upload"/><br/> <input type="submit" value="提交"/> </form> </body> </html>

     

    success.jsp的内容:

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h3>success</h3> </body> </html>

     

    HelloController.java的内容:

    package cn.liuxingchang.controller; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.List; import java.util.UUID; @Controller public class HelloController { /* @RequestMapping("/test") public String test(MultipartFile multipartFile, HttpServletRequest request) throws IOException { String path = request.getSession().getServletContext().getRealPath("/upload/"); File dir = new File(path); if(!dir.exists()) { dir.mkdirs(); } String uuid = UUID.randomUUID().toString().replace("-", ""); String filename = uuid + multipartFile.getOriginalFilename(); multipartFile.transferTo(new File(path, filename)); System.out.println("找不着上传的文件?在这呢:" + path); return "success"; }*/ @RequestMapping("/test") public String test(@RequestParam("upload") MultipartFile multipartFile) throws IOException { multipartFile.transferTo(new File("D:/upload/", multipartFile.getOriginalFilename())); //前提是"D:/upload/"得存在! return "success"; } }

     

    Processed: 0.017, SQL: 8