在POM文件中添加文件处理和文件上传的依赖

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>jstl</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

 

编写Controller:

 1 package com.yas.controller;
 2 
 3 import org.apache.commons.io.FilenameUtils;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.multipart.MultipartFile;
 7 
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11 import java.io.File;
12 import java.io.IOException;
13 import java.util.UUID;
14 
15 @Controller
16 @RequestMapping("/upload")
17 public class UploadController {
18 
19     @RequestMapping("/test1")
20     public String test1(MultipartFile source, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
21         //获取文件信息
22         String filename = source.getOriginalFilename();
23         String contentType = source.getContentType();
24         System.out.println(filename);
25         System.out.println(contentType);
26 
27         String uniqueFilename = UUID.randomUUID().toString();
28         String ext = FilenameUtils.getExtension(filename);
29 
30         //保存文件
31         String realPath = session.getServletContext().getRealPath("/upload");
32         source.transferTo(new File(realPath+"\\"+uniqueFilename+"."+ext));
33         return "hello";
34 
35     }
36 }

 

编写自定义拦截器:

 1 package com.yas.interceptor;
 2 
 3 import org.apache.commons.fileupload.servlet.ServletRequestContext;
 4 import org.springframework.web.multipart.MaxUploadSizeExceededException;
 5 import org.springframework.web.servlet.HandlerInterceptor;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 public class MyFileUploadInterceptor implements HandlerInterceptor {
11     private Long maxFileuploadSize;
12 
13     public Long getMaxFileuploadSize() {
14         return maxFileuploadSize;
15     }
16 
17     public void setMaxFileuploadSize(Long maxFileuploadSize) {
18         this.maxFileuploadSize = maxFileuploadSize;
19     }
20 
21     @Override
22     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
23         //
24         ServletRequestContext serverRequestConext = new ServletRequestContext(request);
25         long l = serverRequestConext.contentLength();
26         if (l > maxFileuploadSize) {
27             throw new MaxUploadSizeExceededException(maxFileuploadSize);
28         }
29         return true;
30     }
31 }

 

修改异常解析器:

 1 package com.yas.resolver;
 2 
 3 import com.yas.ex.MyException1;
 4 import com.yas.ex.MyException2;
 5 import com.yas.ex.MyException3;
 6 import org.springframework.web.multipart.MaxUploadSizeExceededException;
 7 import org.springframework.web.servlet.HandlerExceptionResolver;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 //异常解析器
14 //任何一个hanlder中抛出异常时
15 public class MyExeceptionResolver implements HandlerExceptionResolver {
16     @Override
17     public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
18         ModelAndView modelAndView = new ModelAndView();
19         if(e instanceof MyException1){
20             modelAndView.setViewName("error1");
21         }else if(e instanceof MyException2){
22             modelAndView.setViewName("error2");
23         }else if (e instanceof MyException3){
24             modelAndView.setViewName("error3");
25         }else if(e instanceof MaxUploadSizeExceededException){
26             modelAndView.setViewName("uploaderror");
27         }
28         return modelAndView;
29     }
30 }

 

在mvc.xml中进行配置:

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/upload/test1"></mvc:mapping>
            <bean class="com.yas.interceptor.MyFileUploadInterceptor">
                <property name="maxFileuploadSize" value="1048576"></property>
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 在tomcat 8中,此属性设置无效-->
            <!-- <property name="maxUploadSize" value="1048576"></property>-->
    </bean>

 

编写上传测试页面和错误提示页面:

upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/upload/test1" method="post" enctype="multipart/form-data">
        <input type="file" name="source"><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

 

uploaderror.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    文件上传失败
</body>
</html>

 

posted on 2021-10-27 06:28  Sempron2800+  阅读(3)  评论(0编辑  收藏  举报