SpringMVC处理上传文件

Spring MVC处理文件上传
Spring MVC为文件上传提供了直接支持,这种支持是通过即插即用的MultipartResolver实现. Spring使用Jakarta Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。

在SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要先在上下文中配置MultipartResolver。

  1. 引入jar包!
commons-fileupload.jar

commons-io.jar

  

maven项目pom.xml

  1. <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    配置MultipartResolver
    

      


    配置
 <!--multipartResolver配置 id必须为multipartResolver-->
 <bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
       p:defaultEncoding="UTF-8"
       p:maxUploadSize="5242880"
       p:uploadTempDir="file:/d:/file/temp"
 />

  

  1. 编写控制器和文件上传表单
    编写文件上传表单 upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <center>
      <form method="post" enctype="multipart/form-data" action="user/upload">
           上传图片:
            <input type="file" name="file" />
            <button>提交</button>
      </form>
  </center>
</body>
</html>

  

编写控制器代码

 1. @RequestMapping("/toUpload")  public String toUpload(){
        //跳转到上传页面
        return  "user/upload";  }
    
     @RequestMapping("/upload")  public  String
    saveFile(@RequestParam("file")MultipartFile file) throws IOException
    {
        //接收表单提交的数据,包含文件
        System.out.println("name = " + name);   
         
         // baseurl=D:\workspace_idea1\TestSSM\target\TestSSM\upload\
           String basePath=request.getSession().getServletContext().getRealPath("/upload/");
    
    
            System.out.println(basePath);
    
            try {
                file.transferTo(new File(basePath+file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
             return "success";  }
 

  

 
posted @ 2022-10-26 23:40  呆萌老师  阅读(26)  评论(0编辑  收藏  举报