springmvc:文件的上传与下载

一、文件的上传

1、方式一

(1)基础配置:

pom.xml:导入依赖等:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>pers.zhb</groupId>
    <artifactId>spring_file</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--依赖-->
    <dependencies>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!--servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <!--在bulid中配置resources,防止资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

applicationContext.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="pers.zhb.controller"></context:component-scan>
    <!--静态资源过滤,让Springmvc不处理静态资源,如css、js等-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
    <!--使得注解生效-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--视图解析器,前缀和后缀-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--请求的编码格式,必须和jsp的pageEncoding属性的值保持一致,以便正确读取表单的内容,默认为ISO-8859-1-->
        <!--multipartResolver:以二进制形式传输数据-->
        <property name="defaultEncoding" value="utf-8"></property>
        <!--上传文件大小的上限-->
        <property name="maxUploadSize" value="10485760"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>
</beans>

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">
    <!-- 前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--绑定springmvc的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup><!--启动服务器即创建-->
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>pers.zhb.filter.EncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

过滤器:

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }

(2)文件上传的核心代码:

页面:

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

控制器:

  @RequestMapping("upload")
    //批量上传CommonsMultipartFile为数组即可
    public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request)throws IOException{
        //获取文件名
        String uploadFileName=file.getOriginalFilename();
        //如果文件名为空直接回到首页
        if("".equals(uploadFileName)){
            return "redirect:/index.jsp";
        }
        System.out.println("上传的文件的文件名为:"+uploadFileName);
        //上传路径保存设置
        String path=request.getSession().getServletContext().getRealPath("/upload");
        //如果路径不存在,创建一个
        File realPath =new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("文件保存地址为:"+realPath);
        InputStream inputStream=file.getInputStream();//文件输入流
        OutputStream outputStream=new FileOutputStream(new File(realPath,uploadFileName));//文件输出流,文件的保存地址和文件的文件名
        //读取写入
        int len=0;
        byte[] buffer=new byte[1024];
        while ((len= inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        return "redirect:/index.jsp";
    }

采用缓冲数组的方式读取文件可以加快文件处理的速度

(3)测试:

2、方式二

(1)控制器:

  @RequestMapping("upload")
    public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request)throws IOException{
        //上传路径保存设置
        String path = request.getSession().getServletContext().getRealPath("upload");
        File realPath=new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件的保存地址为:"+realPath);
        //通过commosMultipartFile的方法直接写入文件
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
        return "redirect:/index.jsp";
    }

二、文件的下载

(1)页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <center>
      <h3>
          <a href="${pageContext.request.contextPath}/download">下载图片</a>
      </h3>
  </center>
     </form>
  </body>
</html>

(2)控制器:

 @RequestMapping("download")
    public String download(HttpServletResponse response,HttpServletRequest request)throws Exception{
        //要下载的文件的路径
        String path=request.getSession().getServletContext().getRealPath("/upload");
        String fileName="1.jpg";
        //设置response响应头
        response.reset();//页面不缓存,清空buffer
        response.setCharacterEncoding("utf-8");//字符编码
        response.setContentType("multipart/form-data");//二进制传输数据
        response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
        File file=new File(path,fileName);
        InputStream inputStream=new FileInputStream(file);
        OutputStream outputStream=response.getOutputStream();
        byte[] buff=new byte[1024];
        int index=0;
        //执行写出操作
        while((index=inputStream.read(buff))!=-1){
            outputStream.write(buff,0,index);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        return null;
    }

(3)测试:

 

 

 下载后图片可以正常打开

猜你喜欢

转载自www.cnblogs.com/zhai1997/p/12905884.html