文件的上传与下载在我们的日常工作中十分的常见,在项目开发中也是经常要用到的,springmvc可以更好地支持文件的上传和下载;但是springmvc实现文件的上和下载需要配置一些东西;为了能够支持文件的上传,表单必须使用post方式提交;需要设置enctype属性

enctype="multipart/form-data" method="post"
  •  只有   enctype="multipart/form-data" 才支持文件的上传,表示是以二进制流的形式处理表单数据;
  • application/x-www-form-urlencoded  是enctype 的默认值,只处理表单的 value属性的值;
  • enctype="text/plain"  只会讲空格转换成为+号,其他东西不变,适合于邮件的发送;

 实例:

采用二进制流的形式上传文件

1.首先创建一个新项目;在项目中进行导包;

导包是除了导入springmvc的包之外还要导入文件上传的包

   <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
  </dependency>

2.创建 web.xml的配置文件;

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.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>myFilter</filter-name>
    <!--<filter-class>com.kuang.filter.GenericEncodingFilter</filter-class>-->
    <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>
  <!--/*  包括.jsp-->
  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

3.创建springmvc的配置文件;

在配置spring-servlet.xml文件时注意将bean的id配置为 :  multipartResolver  ,不然会出现400 错误; 因为Springmvc在默认中没有配置MultipartResolver   ,所以在默认中他不能处理文件的上传工作;

<?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
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.zhang.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--ID必须为multipartResolver,否则就400问题-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="1048576"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

</beans>

4.创建一个前端页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>

<form action="/upload" enctype="multipart/form-data" method="post">
    <input type="file" name ="file"/><br>
    <input type="submit" value="upload">
</form>
</body>
</html>

5.创建controller类;

  • Controller实现,必须加上@RequestParam("file")接收文件,主要是用来实现类的分装;
  • 接收文件类型需要设置为CommonsMultipartFile .
package com.zhang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class FileController {
    @RequestMapping("/upload")
    private 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 path = request.getServletContext().getRealPath("/upload");
        File reapath = new File(path);
        if (!reapath.exists()){
            reapath.mkdir();
        }
        //读取写出
        //获取文件输入流
        InputStream ints = file.getInputStream();
        //获取文件输出流
        OutputStream outs = new FileOutputStream(new File(reapath,filename));
        //写出文件
        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=ints.read(bytes))!=-1){
            outs.write(bytes,0,len);
            outs.flush();
        }
        outs.close();
        ints.close();
        return "redirect:/index.jsp";
    }
}

6.进行测试;

测试完成后返回前端页面;就可以查看到上传的文件;

SpringMVC文件上传与下载-LMLPHP

方式二:采用file.transferTo实现文件的上传

@RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request) throws IOException {
        //上传文件的保存路径
        File realPath = new File(request.getServletContext().getRealPath("/upload"));
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //transferTo:将文件写入到磁盘,参数就是一个文件
        file.transferTo(new File (realPath+"/"+file.getOriginalFilename()));
        return "redirect:/index.jsp";
    }

测试完成;

文件的下载实现:

 //文件的下载实现
    /*
    设置响应头
    读取文件
    写出文件
    执行操作
    关闭流
     */

    @RequestMapping("/download")
    public  String download(HttpServletResponse response) throws IOException {
       //要下载的文件的地址
String path="C:\\Users\\张沧\\Desktop";
String filename="5.jpg";
//设置响应头信息
        //使页面不缓存
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Conten-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));

        File file = new File(path, filename);

        //输入输出流
        FileInputStream inputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();

        //执行操作
        int len=0;
        byte[] bytes = new byte[1024];

        while ((len=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        return null;
    }

创建前端页面代码;

<p><a href="${pageContext.request.contextPath}/download">下载图片</a></p>

测试下载成功:

08-06 14:57