一、项目路径

二、代码部分
1、RestFulController.java
package com.qingruan.servlet; import com.qingruan.bean.UserInfo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/restful") public class RestFulController { //MultipartFile类型即为接收上传的文件,参数的名称与input中的name属性的名称一致 @PostMapping("/upload") public String getFile(MultipartFile file, HttpServletRequest request) throws Exception{ //获得文件存储路径(绝对路径) String path = request.getServletContext().getRealPath("/upload"); //获取原文件名 String filename = file.getOriginalFilename(); //创建文件实例 File filePath = new File(path,filename); //如果文件目录不存在,创建目录 if (!filePath.getParentFile().exists()){ filePath.getParentFile().mkdirs(); System.out.println("创建目录:"+filePath); } //写入文件 file.transferTo(filePath); return file.getOriginalFilename(); } }
2、spring-mvc.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: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"> <!--配置spring,创建容器时,扫扫描的包--> <context:component-scan base-package="com.qingruan"></context:component-scan> <!--配置内部视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀和后缀都是与业务逻辑方法值进行组合,组合成jsp文件所在的路径,/hello.jsp--> <property name="prefix" value="/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--配置响应结果的转换器--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <!--将响应结果转换成json格式数据--> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> </list> </property> </bean> <!--文件解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--所有文件大小上限 100M--> <property name="maxUploadSize" value="104857600"/> <!--单个文件大小上限 1M--> <property name="maxUploadSizePerFile" value="1038576"/> <!--编码类型--> <property name="defaultEncoding" value="UTF-8"/> </bean> <!--开启sringmvc框架注解的支持--> <mvc:annotation-driven></mvc:annotation-driven> <!--出现静态资源访问不到的情况,是因为前端控制器会拦截所有的请求,进行处理器的匹配 方式一:开启默认servlet,所有请求都会经过默认servlet请求,如果是静态资源则直接进行响应 <mvc:default-servlet-handler/> --> <!--方式二:设置指定的静态资源访问映射--> <!--<mvc:resources mapping="/img/**" location="/img/"></mvc:resources> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <mvc:resources mapping="/html/**" location="/html/"></mvc:resources> <mvc:resources mapping="/css/**" location="/css/"></mvc:resources> --> </beans>
3、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> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置核心控制器 前端控制器springmvc的集中访问点,负责指定分派 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--设置初始化参数,让程序启动后帮我们加载spring主配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <!--设置servlet拦截的请求路径--> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4、index.jsp
<%-- Created by IntelliJ IDEA. User: 45579 Date: 2022/11/15 Time: 20:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> <% pageContext.setAttribute("page",request.getContextPath());%> <!--绝对url指向指定栈点--> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script> $(function (){ $("#btn").click(function () { var user={age:21,name:"zhangsan",phone:"111222333"}; $.ajax({ type:"POST", data:JSON.stringify(user), url:"${page}/getUser", contentType:"application/json;charset=utf-8", success:function (data) { console.log(data.age); } }) }) }) </script> </head> <body> <input type="button" id="btn" value="submitUser"/> <%--<img src="${page}/img/1.jpg">--%> </body> </html>
5、fileUpload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> <% pageContext.setAttribute("page",request.getContextPath());%> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <form action="${page}/restful/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="upload"> </form> </body> </html>
三、运行效果
连接tomcat

控制台

文件中的位置

四、多文件上传
其他配置的代码不变,以下文件要在上述基础上修改
运行效果
前端

控制台

本文详细介绍了如何在SpringMVC项目中实现文件上传,包括单文件和多文件上传。首先,文章给出了项目的目录结构,然后逐步解析了RestFulController.java、spring-mvc.xml、web.xml、index.jsp以及fileUpload.jsp等关键代码部分。在运行效果部分,作者展示了在连接Tomcat后,文件成功上传到服务器的控制台输出和文件存储位置。最后,针对多文件上传,文章指出需要对现有配置进行哪些修改,并提供了前端和控制台的运行情况。

3289

被折叠的 条评论
为什么被折叠?



