录:

1、springmvc文件下载
2、springmvc文件上传
3、下载excel模板的demo
4、导入excel数据的demo

 

1、springmvc文件下载    <--返回目录

转自:springmvc文件下载

1.1、

文件下载是web项目中常用的服务,在springmvc中常用ResponseEntity类来事项文件下载

1.2、ResponseEntity

ResponseEntity类实现响应头、文件数据(以字节存储)、状态封装在一起交给浏览器处理以实现浏览器的文件下载。简单的说ResponseEntity可以折这HttpHeaders和HttpStatus,通过对HttpHeaders和HttpStatus的设置可以使浏览器执行下载操作。

1.3、实现文件下载

步骤

  1. 获取到文件的存放的真实路径
  2. 根据接收到的文件名和文件真实路径创建文件实例(注意:这里不是创建一个文件,而是创建一个File型的实例)
  3. 设置响应头Content-Disposition浏览器根据这个响应头执行相应的操作和要下载的文件名
  4. 设置响应内容的MIME类型,以二进制流形式传输
  5. 返回ResponseEntity
@RequestMapping("/download")
public ResponseEntity<byte[]> download(@RequestParam("fileName") String fileName, HttpServletRequest req)
        throws IOException {

    // 获取文件存放的真实路径
    String realPath = req.getServletContext().getRealPath("/WEB-INF/file");
    //创建文件实例
    File file = new File(realPath, fileName);
    //修改文件名的编码格式
    String downloadFileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
    
    //设置httpHeaders,使浏览器响应下载
    HttpHeaders headers = new HttpHeaders();
    //告诉浏览器执行下载的操作,“attachment”告诉了浏览器进行下载,下载的文件 文件名为 downloadFileName
    headers.setContentDispositionFormData("attachment", downloadFileName);
    //设置响应方式为二进制,以二进制流传输
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

1.4、火狐浏览器测试

  从图中我们可以看到,我们设置的Content-Disposition起效果,传输类型也为二进制。

springmvc文件上传和下载,下载excel模板和导入excel数据(poi解析)

 

2、springmvc文件上传    <--返回目录

转自:springmvc文件上传

2.1、

文件的上传与下载基本上是web项目中会用到的技术,在web学习中我们用到的是 Apache fileupload这个组件来实现上传,在springmvc中对它进行了封装,让我们使用起来比较方便,但是底层还是由Apache fileupload来实现的。springmvc中由MultipartFile接口来实现文件上传。

2.2、MultipartFile接口

该接口用来实现springmvc中的文件上传操作,它有两个实现类:

springmvc文件上传和下载,下载excel模板和导入excel数据(poi解析)

 

 接口定义的方法:

springmvc文件上传和下载,下载excel模板和导入excel数据(poi解析)

 

2.3、实现文件上传

导入jar包

  • commons-fileupload
  • commons-io

commons-io可以不用自己导入,maven会自动导入对应版本的jar

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

前端jsp页面

  • input的type设置为file

  • form表单的method设为post,

  • form表单的enctype设置为multipart/form-data,以二进制的形式传输数据。

<%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <form action="/ssm/file/imgUpload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"><br><br>
    <input type="submit" value="上传">
  </form>
</body>
</html>

Controller层接收

使用MultipartFile对象作为参数,接收前端发送过来的文件,将文件写入本地文件中,就完成了上传操作

@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
        throws IllegalStateException, IOException {

    // 判断文件是否为空,空则返回失败页面
    if (file.isEmpty()) {
        return "failed";
    }
    // 获取文件存储路径(绝对路径)
    String path = req.getServletContext().getRealPath("/WEB-INF/file");
    // 获取原文件名
    String fileName = file.getOriginalFilename();
    // 创建文件实例
    File filePath = new File(path, fileName);
    // 如果文件目录不存在,创建目录
    if (!filePath.getParentFile().exists()) {
        filePath.getParentFile().mkdirs();
        System.out.println("创建目录" + filePath);
    }
    // 写入文件
    file.transferTo(filePath);
    return "success";
}  

springmvc.xml配置CommonsMultipartResolver

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--上传文件的最大大小,单位为字节 --> 
    <property name="maxUploadSize" value="17367648787"></property>
     
    <!-- 上传文件的编码 -->
    <property name="defaultEncoding" value="UTF-8"></property>
</bean>

 

3、下载excel模板的demo    <--返回目录

springmvc文件上传和下载,下载excel模板和导入excel数据(poi解析)

  excel模板设置单元格数据格式

springmvc文件上传和下载,下载excel模板和导入excel数据(poi解析)

 

   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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.oy</groupId>
    <artifactId>boot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

相关文章: