SpingMVC——文件的上传下载

SpingMVC——文件的上传下载

一、文件上传

文件上传所需要的jar包:commons-fileupload

我们要想使用文件上传功能就必须导入commons-fileupload这个依赖包,它会自动帮我们导入他的依赖包 commons-io包

    <!--文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
一个重要的配置:上传文件解析器——MultipartResolver

SpringMVC可以很好的支持文件上传,但是SpringMVC上下文中没有默认装配MultipartResolver,因此在默认情况下不能处理文件上传工作。如果想要使用Spring的文件上传功能,就需要在SpringMVC上下文中配置MultipartResolver。

MultipartResolver 用于处理文件上传,当收到请求时 DispatcherServlet 的 checkMultipart() 方法会调用 MultipartResolver 的 isMultipart() 方法判断请求中是否包含文件。如果请求数据中包含文件,则调用 MultipartResolver 的 resolveMultipart() 方法对请求的数据进行解析,然后将文件数据解析成 MultipartFile 并封装在 MultipartHttpServletRequest (继承了 HttpServletRequest) 对象中,最后传递给 Controller

我们可以看到MultipartResolver里面有三个方法
在这里插入图片描述
在springmvc-config.xml中配置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.muhan.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>
    <!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置文件上传请求的编码格式,默认为ISO-8859-1 。必须与jsp的pageEncoding属性一致,以便于正确的读取表单内容-->
        <property name="defaultEncoding" value="utf-8"/>
        <!--设置文件上传大小上线,单位为字节;10485760B=10M-->
        <property name="maxUploadSize" value="10485760"/>
        <!--设置缓冲区大小-->
        <property name="maxInMemorySize" value="40960"/>
    </bean>
</beans>

注意事项:bean的id必须为multipartResolver,否则上传文件会报404错误

在表单上的处理

首先:我们为了能上传文件,表单请求必须使用POST请求,并将enctype设置为multipart/form-data。

enctype的几个属性:

  • application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。
  • multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
  • text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。
<form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

一旦我们将enctype设置为multipart/form-data,浏览器就会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器解析原始的HTTP响应。

实现方式一:使用流的方式上传文件

在controller编写业务逻辑

//注意:必须在文件参数前加上@RequestParam注解,是用来将文件封装成CommonsMultipartFile对象的,不加就报错
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //获取文件名:
        String filename = file.getOriginalFilename();
        //判断文件是否为空,如果为空直接回到首页
        if (filename.equals("")){
            return "redirect:/index.jsp";
        }
        System.out.println("调试信息:上传的文件名--------->>>>>>"+filename);

        //设置上传保存路径
        String path = request.getServletContext().getRealPath("/upload");
        System.out.println("调试信息:上传文件保存地址path--------->>>>>>"+path);
        //如果路径不存在,就创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("调试信息:上传文件保存地址realPath--------->>>>>>"+realPath);

        //获取文件输入流
        InputStream in = file.getInputStream();
        //创建文件输出流,关联上传文件保存地址和文件名
        FileOutputStream out = new FileOutputStream(new File(realPath, filename));

        //读取和写处
        int len=0;
        byte[] bytes = new byte[1024 * 8];//创建一个缓冲区,提高效率
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
            out.flush();
        }
        in.close();
        out.close();
        //重定向到首页
        return "redirect:/index.jsp";
    }

测试:
在这里插入图片描述
选文件后点击提交
在这里插入图片描述
我们可以发现在我们项目的target目录下生成了一个upload目录,该目录下就是我们上传的文件
在这里插入图片描述

实现方式二:使用file.Transto 上传文件
@RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //设置上传的保存路径
        String path = request.getServletContext().getRealPath("/upload2");
        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";
    }

在这里插入图片描述
点击提交在target的项目目录下会新建一个upload2目录,上传的文件就在该目录下
在这里插入图片描述

二、文件下载

编写controller

    @RequestMapping("/download")
    public String download(HttpServletResponse response) throws IOException {

        //1.准备工作
        //要下载的文件地址
        String path = "C:/Users/困困/Desktop/";
        //要下载的文件名
        String fileName="阿里面试题.md";
        //封装文件
        File file = new File(path,fileName);

        //2.设置response响应头
        response.reset();//设置页面重启,不留缓存,清空buffer
        response.setCharacterEncoding("UTF-8");//设置字符编码
        response.setContentType("multipart/form-data");//设置内容格式为二进制传输数据
        response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));//设置响应头

        //3.读取文件,创建输入流
        FileInputStream in = new FileInputStream(file);

        //4.写出文件,获取输出流
        OutputStream out = response.getOutputStream();

        byte[] bytes = new byte[1024 * 8];//创建一个缓冲区
        int len=0;
        while ((len=in.read(bytes))!=-1){
            out.write(bytes,0,len);
            out.flush();
        }
        out.close();
        in.close();


        return null;
    }

编写jsp

<a href="${pageContext.request.contextPath}/download">点击下载</a>

测试:
在这里插入图片描述
点击下载之后
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值