• SpringMVC实现文件的上传(CommonsMultipartResolver和StanderServletMultipartResolver)


         一定要足够优秀才能堵住悠悠众口。

    b14fbd0383c74866b141a8322afde37c.jpg

     

    文件上传功能在SpringMVC中有两种方法(两种不同的处理器)

    2df7c8607da74692b9cbedeb95edd23c.png

     这篇文章我们将通过这两种方法来实现文件上传功能

    1:CommonsMultipartResolver

    创建一个新的Maven项目并在项目中进行基础的环境配置

    Maven项目基础配置,如果不同可以参考一下

    一:在pom.xml中导入我们即将用到的依赖

    1. <dependency>
    2. <groupId>commons-fileuploadgroupId>
    3. <artifactId>commons-fileuploadartifactId>
    4. <version>1.4version>
    5. dependency>

    二:创建网页,实现前端出现页面

    注意:这里创建的是动态网页

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Titletitle>
    5. head>
    6. <body>
    7. <form action="/play" method="post" enctype="multipart/form-data">
    8. <input type="file" name="file">
    9. <input type="submit" value="提交">
    10. form>
    11. body>
    12. html>

    三:创建SpringMVC框架的控制器

    1. package fileupload_demo1;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.GetMapping;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.ResponseBody;
    6. import org.springframework.web.multipart.MultipartFile;
    7. import javax.servlet.http.HttpServletRequest;
    8. import java.io.File;
    9. import java.io.IOException;
    10. import java.text.SimpleDateFormat;
    11. import java.util.Date;
    12. import java.util.UUID;
    13. @Controller
    14. public class CT1 {
    15. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/"); //创建日期,并标注时间显示格式
    16. @GetMapping("/upload")
    17. public String play1(){
    18. return "hh";
    19. }
    20. @RequestMapping("/play")
    21. @ResponseBody
    22. public String play1(MultipartFile file, HttpServletRequest req) throws IOException {
    23. String format = simpleDateFormat.format(new Date()); //获取今天的日期
    24. String realpath = req.getServletContext().getRealPath("/img") +format; //获取Tomcat中的临时储存文件
    25. File folder = new File(realpath);
    26. if(!folder.exists()){ //检查目录是否存在
    27. folder.mkdirs(); //目录不存在进行创建
    28. }
    29. String oldname = file.getOriginalFilename(); //得到上传时的文件名
    30. String name = UUID.randomUUID().toString()+oldname.substring(oldname.lastIndexOf(".")); //UUID.randomUUID().toString():Java中自动生成主键的方法,机器中生成的一串生成数字
    31. file.transferTo(new File(folder,name)); //将前端传来的数据保存指定名字保存在指定文件夹下
    32. String url = req.getScheme()+ "://"+req.getServerName() +":"+req.getServerPort() +"/img" +format +name;
    33. return url;
    34. //http://localhost:8080/img/2022/11/13/8d3910d1-2a7c-47ce-8251-3cc4eeaf0bc4.jpeg
    35. }
    36. }

    注意:下面标注了代码获取的结果

    c7e57f38f15648e2903bf070bce07685.png

     四:配置SpringMVC

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. 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 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    7. <context:component-scan base-package="fileupload_demo1">context:component-scan>
    8. <mvc:annotation-driven/>
    9. <mvc:resources mapping="/**" location="/">mvc:resources>
    10. <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
    11. <property name="defaultEncoding" value="UTF-8"/>
    12. <property name="maxUploadSize" value="1048576"/>
    13. <property name="maxUploadSizePerFile" value="1048576"/>
    14. <property name="maxInMemorySize" value="4096"/>
    15. <property name="uploadTempDir" value="file:///E:\\tmp"/>
    16. bean>
    17. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="modelAndView">
    18. <property name="prefix" value="/jsp/">property>
    19. <property name="suffix" value=".jsp">property>
    20. bean>
    21. beans>

    执行项目:

    前端网页:

    0893f00d25ef4ecb88d7e0833eb3addf.png

     点击提交,返回图片url

    1df96c4c39744615917a806dc7b1bc70.png

     最终结果:

    ba53f451a60543008c13a6551ab9517b.png

     2:StanderServletMultipartResolver(经常被使用)

    这种方法的配置基本上与第一种方法相同,没有很大的区别

    区别一:将SpringMVC的配置文件中文件上传的类进行更换

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. 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 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    7. <context:component-scan base-package="fileupload_demo1">context:component-scan>
    8. <mvc:annotation-driven/>
    9. <mvc:resources mapping="/**" location="/">mvc:resources>
    10. <bean class="org.springframework.web.multipart.support.StandardServletMultipartResolver" id="multipartResolver">bean>
    11. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="modelAndView">
    12. <property name="prefix" value="/jsp/">property>
    13. <property name="suffix" value=".jsp">property>
    14. bean>
    15. beans>

    区别二:将上传文件的参数配置放在web.xml中

    1. "1.0" encoding="UTF-8"?>
    2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    5. version="4.0">
    6. <context-param>
    7. <param-name>contextConfigLocationparam-name>
    8. <param-value>classpath:spring.xmlparam-value>
    9. context-param>
    10. <listener>
    11. <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    12. listener>
    13. <servlet>
    14. <servlet-name>springmvcservlet-name>
    15. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    16. <init-param>
    17. <param-name>contextConfigLocationparam-name>
    18. <param-value>classpath:SpringMVC.xmlparam-value>
    19. init-param>
    20. <multipart-config>
    21. <max-file-size>1048576max-file-size>
    22. <max-request-size>1048576max-request-size>
    23. <file-size-threshold>4096file-size-threshold>
    24. multipart-config>
    25. servlet>
    26. <servlet-mapping>
    27. <servlet-name>springmvcservlet-name>
    28. <url-pattern>/url-pattern>
    29. servlet-mapping>
    30. <filter>
    31. <filter-name>encodingfilter-name>
    32. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    33. <init-param>
    34. <param-name>encodingparam-name>
    35. <param-value>UTF-8param-value>
    36. init-param>
    37. <init-param>
    38. <param-name>forceRequestEncodingparam-name>
    39. <param-value>trueparam-value>
    40. init-param>
    41. <init-param>
    42. <param-name>forceResponseEncodingparam-name>
    43. <param-value>trueparam-value>
    44. init-param>
    45. filter>
    46. <filter-mapping>
    47. <filter-name>encodingfilter-name>
    48. <url-pattern>/*url-pattern>
    49. filter-mapping>
    50. web-app>

    其他的内容不变实现的功能是相同的结果

     

     

  • 相关阅读:
    Centos系统常见配置(详细)总结
    VoLTE端到端业务详解 | 掉话问题
    秋招求职经验分享
    助力水泥基建裂痕自动化巡检,基于yolov5融合ASPP开发构建多尺度融合目标检测识别系统
    ERR_FAILED 200 解决方案
    数字生活的未来:探索Web3的全新世界
    【k8s源码篇之Informer篇4】关于 Informer 的一些困惑点
    群体优化算法----火山爆发算法介绍以及离散优化Pareto最优解示例
    oracle 数据链接过多,导致后续链接链接不上
    【代码规范】switch 块级的作用域问题
  • 原文地址:https://blog.csdn.net/m0_52479012/article/details/127832868