资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

SpringMVC实现文件的上传和下载

SpringMVC 中,文件的上传,是通过 MultipartResolver 实现的。 所以,如果要实现文件的上传,只要在 spring-mvc.xml 中注册相应的 MultipartResolver 即可。

成都创新互联长期为超过千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为即墨企业提供专业的成都做网站、成都网站设计、成都外贸网站建设即墨网站改版等技术服务。拥有十余年丰富建站经验和众多成功案例,为您定制开发。

MultipartResolver 的实现类有两个:

CommonsMultipartResolver
StandardServletMultipartResolver
两个的区别:

第一个需要使用 Apache 的 commons-fileupload 等 jar 包支持,但它能在比较旧的 servlet 版本中使用。
第二个不需要第三方 jar 包支持,它使用 servlet 内置的上传功能,但是只能在 Servlet 3 以上的版本使用。
第一个使用步骤:

/CommonsMultipartResolver 上传用到的两个包/

"commons-fileupload:commons-fileupload:1.3.1",

"commons-io:commons-io:2.4"
如果是maven项目的话直接导入:


commons-fileupload
commons-fileupload
1.3.1

dispatcher-servlet.xml配置:


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">









    
    
    
    



    
    

web.xml:


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">



    dispatcher
    org.springframework.web.servlet.DispatcherServlet
    
        contextConfigLocation
        classpath:dispatcher-servlet.xml
    


    dispatcher
    /

后台java(上传、下载)处理代码:

package edu.nf.ch08.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;

/**

  • @author wangl
  • @date 2018/11/2*/
    @Controller
    br/>*/
    @Controller

    /**

    • 文件上传只需要Spring传入一个MultipartFile对象即可,
    • 这个对象可以获取文件相关上传的信息。
    • 一个MultipartFile表示单个文件上传,当需要上传多个文件时
    • 只需要声明为MultipartFile[]数组即可。
    • @return*/
      @PostMapping("/upload")
      br/>*/
      @PostMapping("/upload")
      //获取当前系统用户目录
      String home = System.getProperty("user.home");
      //指定上传的文件夹目录
      File uploadDir = new File(home + "/files");
      //如果目录不存在,则创建
      if(!uploadDir.exists()){
      uploadDir.mkdir();
      }
      //获取上传的文件名
      String fileName = file.getOriginalFilename();
      //构建一个完整的文件上传对象
      File uploadFile = new File(uploadDir.getAbsolutePath() + "/" + fileName);
      try {
      //通过transferTo方法进行上传
      file.transferTo(uploadFile);
      } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
      }
      //将文件名存入Model,转发到index页面
      ModelAndView mv = new ModelAndView("index");
      mv.addObject("fileName", fileName);
      return mv;
      }

    /**

    • 文件下载
    • 读取服务器本地文件并封装为ResponseEntity对象
    • 响应客户端,写回的是一个字节数组
    • @param fileName 文件名
    • @return*/
      @GetMapping("/download")
      br/>*/
      @GetMapping("/download")
      download(String fileName){
      //依据文件名构建本地文件路径
      String filePath = System.getProperty("user.home") + "/files/" + fileName;
      //依据文件路径构建File对象
      File file = new File(filePath);
      //创建响应头对象,设置响应信息
      HttpHeaders headers = new HttpHeaders();
      try {
      //对文件名进行重新编码,防止在响应头中出现中文乱码
      String headerFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
      //设置响应内容处理方式为附件,并指定文件名
      headers.setContentDispositionFormData("attachment", headerFileName);
      //设置响应头类型为application/octet-stream,表示是一个流类型
      headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
      //将文件转换成字节数组
      byte[] bytes = FileUtils.readFileToByteArray(file);
      //创建ResponseEntity对象(封装文件字节数组、响应头、响应状态码)
      ResponseEntity entity = new ResponseEntity<>(bytes, headers, HttpStatus.CREATED);
      //最后将整个ResponseEntity对象返回给DispatcherServlet
      return entity;
      } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("文件下载失败");
      }
      }
      }

上传文件的网页html:





Title


文件上传




File:




Spring MVC 实现文件的上传和下载

上传成功后转发的jsp(下载文件)页面:
<%--
Created by IntelliJ IDEA.
User: wangl
Date: 2018/11/2
Time: 09:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


Title


${fileName}

Spring MVC 实现文件的上传和下载

项目结构:

Spring MVC 实现文件的上传和下载


文章题目:SpringMVC实现文件的上传和下载
文章路径:http://cdkjz.cn/article/gcgcci.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220