【SpringMVC】(十)文件上传与下载

文件上传与下载

参考:狂神说SpringMVC08:拦截器+文件上传下载


环境搭建

  • pom.xml增加

    		<!--文件上传-->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.4</version>
            </dependency>
            <!--高版本的servlet-api-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.1</version>
                <scope>provided</scope>
            </dependency>
    
  • web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    
        <!--1. 注册DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <!--启动级别-1-->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <!-- / 和/* 的区别-->
        <!-- / 匹配所有的请求:(不包括.jsp)-->
        <!-- /* 匹配所有的请求:(包括.jsp)-->
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    
        <!--SpringMVC提供的乱码过滤器-->
        <filter>
            <filter-name>encoding</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>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    
  • springmvc-servlet.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
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
        <context:component-scan base-package="com.musecho.controller"/>
    
        <!--视图解析器ViewResolver:解析DispatcherServlet传递来的ModelAndView-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
            <!--前缀-->
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <!--后缀-->
            <property name="suffix" value=".jsp"/>
        </bean>
    
    
        <!--JSON乱码问题配置-->
        <mvc:annotation-driven>
            <mvc:message-converters register-defaults="true">
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                            <property name="failOnEmptyBeans" value="false"/>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
    
    </beans>
    


1. 文件上传

  • 若要使用Spring的文件上传功能,需要在上下文中国配置MultipartResolver。

    springmvc-servlet.xml添加配置

    	<!--文件上传配置-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!--请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1-->
            <property name="defaultEncoding" value="utf-8"/>
            <!--上传文件大小上限,单位为字节(10485760=10M)-->
            <property name="maxUploadSize" value="10485760"/>
            <!--上传文件大小的阀值,低于阀值保存在内存,高于阀值生成硬盘上的临时文件-->
            <property name="maxInMemorySize" value="40960"/>
        </bean>
    
  • 前端表单:为了能上传文件,method方法必须设置为post,并将enctype设置为multipart/form-data,这样才能使文件以二进制数据形式发送给服务器。

    index.jsp

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

    @RestController
    public class FileController {
    
        //@RequestParam("file) 将name=file控件得到的文件封装成CommonsMultipartFile对象
        //批量上传CommonsMultipartFile为数组即可
        @RequestMapping("/upload")
        public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    
            //获取文件名,若为空则返回上传页面
            String fileName = file.getOriginalFilename();
            if ("".equals(fileName)) {
                return "redirect:/index.jsp";
            }
            System.out.println("文件名:" + fileName);
    
    
            //设置上传文件保存路径
            String filePath = request.getServletContext().getRealPath("/upload");
            //若路径不存在,创建一个
            File realPath = new File(filePath);
            if (!realPath.exists()) {
                realPath.mkdir();
            }
            System.out.println("文件保存路径:" + realPath);
    
    
            //读取写出
            InputStream is = file.getInputStream();
            OutputStream os = new FileOutputStream(new File(realPath, fileName));
    
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
                os.flush();
            }
            os.close();
            is.close();
    
    
            return "redirect:/index.jsp";
        }
    
        //采用file.transferTo方法保存上传文件
        @RequestMapping("/upload2")
        public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    
            //上传路径保存设置
            String path = request.getServletContext().getRealPath("/upload");
            File realPath = new File(path);
            if (!realPath.exists()) {
                realPath.mkdir();
            }
            System.out.println("上传文件地址:" + realPath);
    
    
            //通过CommonsMultipartFile的方法直接写文件
            file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
    
    
            return "redirect:/index.jsp";
        }
    
        
    
    }
    
  • 上传成功



2. 文件下载

  • index.jsp添加

    <a href="${pageContext.request.contextPath}/download">点击这里可以下载图片</a>
    
  • FileController添加

    	@RequestMapping("/download")
        public String downloads(HttpServletResponse response, HttpServletRequest request) throws IOException {
            //要下载的图片地址
            String path = request.getServletContext().getRealPath("/upload");
            String filename="1.png";
    
    
            //1.设置response响应头
            response.reset();//设置页面不缓存,清空buffer
            response.setCharacterEncoding("UTF-8");//字符编码
            response.setContentType("multipart/form-data");//二进制传输数据
            //设置响应头
            response.setHeader("Content-Dispositon", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
    
            File file2 = new File(path, filename);
            //2.读取文件--输入流
            InputStream is = new FileInputStream(file2);
            //3.写出文件--输出流
            OutputStream os = response.getOutputStream();
    
            //4.执行 写出操作
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }
            os.close();
            is.close();
    
            return null;
        }
    
  • 文件放在这里

posted @ 2021-02-24 16:00  musecho  阅读(84)  评论(0)    收藏  举报