CRUD和文件上传下载

一、CRUD

1.1Pom.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>org.example</groupId>
  <artifactId>testssm02</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>testssm02 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>

    <!--添加jar包依赖-->
    <!--1.spring 5.0.2.RELEASE相关-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!--2.mybatis相关-->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql-->
    <mysql.version>5.1.44</mysql.version>
    <!--pagehelper分页jar依赖-->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!--mybatis与spring集成jar依赖-->
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <!--3.dbcp2连接池相关 druid-->
    <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    <commons.pool2.version>2.4.3</commons.pool2.version>
    <!--4.log日志相关-->
    <log4j2.version>2.9.1</log4j2.version>
    <!--5.其他-->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <lombok.version>1.18.2</lombok.version>
  </properties>

  <dependencies>
    <!--1.spring相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--2.mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!--pagehelper分页插件jar包依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!--mybatis与spring集成jar包依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>

    <!--3.dbcp2连接池相关-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>${commons.dbcp2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>${commons.pool2.version}</version>
    </dependency>

    <!--4.log日志相关依赖-->
    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
    </dependency>

    <!--5.其他-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- jsp依赖-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>testssm02</finalName>
    <resources>
      <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>jdbc.properties</include>
          <include>*.xml</include>
        </includes>
      </resource>
    </resources>

    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>${maven.compiler.plugin.version}</version>
          <configuration>
            <source>${maven.compiler.source}</source>
            <target>${maven.compiler.target}</target>
            <encoding>${project.build.sourceEncoding}</encoding>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.2</version>
          <dependencies>
            <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
            <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>${mysql.version}</version>
            </dependency>
          </dependencies>
          <configuration>
            <overwrite>true</overwrite>
          </configuration>
        </plugin>

        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

1.2.相关配置文件

applicationContext.xml
applicationContext-mybatis.xml
generatorConfig.xml
jdbc.properties
log4j2.xml
mybatis.cfg.xml
springmvc-servlet.xml

1.3.web.xml相关配置

<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_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 读取Spring上下文的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- Spring MVC servlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <!--web.xml 3.0的新特性,是否支持异步-->
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 中文乱码处理 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--web.xml 3.0的新特性,是否支持异步-->
    <async-supported>true</async-supported>
    <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>

1.4.逆向生成

将t_struts_class表逆向生成出Model、Mapper.xml、Mapper.java
分页查询补充

Mapper配置文件

<select id="listPager" parameterType="com.yzp.model.Clayy" resultType="com.yzp.model.Clayy">
  select
  <include refid="Base_Column_List" />
  from t_struts_class
  <where>
    <if test="cname != null and cname != ''">
      cname like CONCAT('%',#{cname},'%')
    </if>
    <if test="cid != null and cid != ''">
      cid = #{cid}
    </if>
  </where>
  </select>

Mapper层

List<Clayy> listPager(Clayy clayy);

Service层

 @Override
    public List<Clayy> listPager(Clayy clayy, PageBean pageBean) {
        return clayyMapper.listPager(clayy);
    }

1.5.代码开发

注意:记得配置aop分页切面
==PagerAspect ==

package com.yzp.util;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
@Aspect
public class PagerAspect {

    /**
     * *:返回值类型
     * *..:无限包
     * *Service:以Service结尾接口名
     * *Pager:以Pager方法
     * 只要同时匹配上诉四个条件,就会被列为目标对象
     * 上述配置要生效,代理注解<aop:aspectj-autoproxy/>不能少
     * @param args
     * @return
     * @throws Throwable
     */
    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        Object[] params = args.getArgs();
        PageBean pageBean = null;
        for (Object param : params) {
            if(param instanceof PageBean){
                pageBean = (PageBean)param;
                break;
            }
        }

        if(pageBean != null && pageBean.isPagination())
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());

//        执行目标方法
        Object list = args.proceed(params);

        if(null != pageBean && pageBean.isPagination()){
            PageInfo pageInfo = new PageInfo((List) list);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return list;
    }


}

1.5.1 Web层

package com.yzp.controller;

import com.yzp.biz.ClayyBiz;
import com.yzp.model.Clayy;
import com.yzp.model.dto.ClayyDto;
import com.yzp.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author易泽鹏
 * @site 16670388677
 * @company
 * @create  2022-08-17 19:51
 */
@Controller
@RequestMapping("/cly")
public class ClayycController {

    @Autowired
    private ClayyBiz clayyBiz;
    //list->clylist
    // tolist->重定向list->"redirect:/cly/list"
    // toedit->跳转编辑页面->clyEdit
    //clayy:以前是通过模型驱动接口封装,现在是直接在方法中接收参数即可


    @RequestMapping("/list")
    public  String list(Clayy clayy, HttpServletRequest request){
       PageBean  pageBean = new PageBean();
       pageBean.setRequest(request);
        List<Clayy> lst = this.clayyBiz.listPager(clayy, pageBean);
        request.setAttribute("lst",lst);
        request.setAttribute("pageBean",pageBean);
        return  "clylist";
    }
    @RequestMapping("/toEdit")
    public  String toEdit(Clayy clayy, HttpServletRequest request){
        Integer cid = clayy.getCid();
        //传递的id代表了修改,没传代表新增
        if(cid!=null){
            List<Clayy> lst = this.clayyBiz.listPager(clayy, null);
            request.setAttribute("b",lst.get(0));
        }
        return  "clyedit";
    }
    @RequestMapping("/add")
    public  String add(Clayy clayy){
        this.clayyBiz.insertSelective(clayy);
        return  "redirect:/cly/list";
    }

    /**
     * @valid 是与实体类中的服务端校验 注解配合使用的
     * @param clayy
     * @param bindingResult  存放了所有违背 校验的错误信息
     * @return
     */
    @RequestMapping("/valiAdd")
    public  String valiAdd(@Valid Clayy clayy, BindingResult bindingResult,HttpServletRequest request){
        if(bindingResult.hasErrors()){
            Map msg = new HashMap();
//            违背规则
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //cid :cid不能为空
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
                msg.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
                request.setAttribute("msg",msg);
            //如果出现了错误,应该将提示语显示在表单提示元素后方
            return  "clyedit";
        }else {
            this.clayyBiz.insertSelective(clayy);
        }
        return  "redirect:/cly/list";
    }

    @RequestMapping("/del")
    public  String del(Clayy clayy){
        this.clayyBiz.deleteByPrimaryKey(clayy.getCid());
        return  "redirect:/cly/list";
    }
    @RequestMapping("/edit")
    public  String edit(Clayy clayy){
        this.clayyBiz.updateByPrimaryKeySelective(clayy);
        return  "redirect:/cly/list";
    }

}

1.5.2页面层

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link
            href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
            rel="stylesheet">
    <script
            src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    <title>班级相册</title>
    <style type="text/css">
        .page-item input {
            padding: 0;
            width: 40px;
            height: 100%;
            text-align: center;
            margin: 0 6px;
        }

        .page-item input, .page-item b {
            line-height: 38px;
            float: left;
            font-weight: 400;
        }

        .page-item.go-input {
            margin: 0 10px;
        }
    </style>
</head>
<body>
<form class="form-inline"
      action="${pageContext.request.contextPath }/cly/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="cname"
               placeholder="请输入班级名称">
    </div>
    <button type="submit" class="btn btn-primary mb-2">查询</button>
    <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/cly/toEdit">新增</a>
</form>

<table class="table table-striped bg-success">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">班级名称</th>
        <th scope="col">指导老师</th>
        <th scope="col">班级相册</th>
        <th scope="col">操作</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach  var="b" items="${lst }">
        <tr>
            <td>${b.cid }</td>
            <td>${b.cname }</td>
            <td>${b.cteacher }</td>
            <td>
                <img src="${pageContext.request.contextPath }${b.pic}"  style="height: 100px;width: 100px;"/>

            </td>
            <td>
                <a href="${pageContext.request.contextPath }/cly/toEdit?cid=${b.cid}">修改</a>
                <a href="${pageContext.request.contextPath }/cly/del?cid=${b.cid}">删除</a>
                <a href="${pageContext.request.contextPath }/clyUpload.jsp?cid=${b.cid}">上传图片</a>
                <a href="${pageContext.request.contextPath }/cly/download?cid=${b.cid}">下载图片</a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<z:page pageBean="${pageBean }"></z:page>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>班级的编辑界面</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/cly/${empty b ? 'add' : 'edit'}" method="post">
    cid:<input name="cid" type="text" value="${b.cid }"><span style="color: red">${msg.cid}</span><br>
    cname:<input type="text" name="cname" value="${b.cname }"><span style="color: red">${msg.cname}</span><br>
    cteacher:<input type="text" name="cteacher" value="${b.cteacher }"><span style="color: red">${msg.cteacher}</span><br>
    pic:<input type="text" name="pic" value="${b.pic }"><br>
    <input type="submit">
</form>
</body>
</html>

运行结果:
在这里插入图片描述

二、文件上传

2.1pom依赖

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

2.2Springmvc.xml配置

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

2.3前台

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/19
  Time: 21:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/cly/upload" method="post" enctype="multipart/form-data">
<input type="test" value="${param.cid}" name="cid">
    <input type="file" name="picFile">
    <input type="submit">
</form>
</body>
</html>

2.4后台

建一个dto类

package com.yzp.model.dto;

import com.yzp.model.Clayy;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author易泽鹏
 * @site 16670388677
 * @company
 * @create  2022-08-19 21:19
 */
public class ClayyDto extends Clayy {

    //MultipartFile的属性名一定要跟form中的表单属性名一致
    private MultipartFile picFile;

    public MultipartFile getPicFile() {
        return picFile;
    }

    public void setPicFile(MultipartFile picFile) {
        this.picFile = picFile;
    }
}

上传方法

 @RequestMapping("/upload")
    public  String upload(ClayyDto clayyDto){
        try {
            //前台上传文件
            MultipartFile picFile = clayyDto.getPicFile();
            //实际应该配置resource.properties中
            String diskPath="K:/temp/images/";//图片的存放地址
            //http://localhost:8080/upload/mvc/0516.png
            String requestPath="/upload/mvc/";//数据库保存的地址,也是我们访问的地址


            //拿到上传文件的名字
            String fileName = picFile.getOriginalFilename();//0516.png
            FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(diskPath+fileName));

            //将图片上传之后,并且将图片地址更新到数据库中
            Clayy clayy = new Clayy();
            clayy.setCid(clayyDto.getCid());
            clayy.setPic(requestPath+fileName);
            this.clayyBiz.updateByPrimaryKeySelective(clayy);
        }catch (Exception e){
            e.printStackTrace();
        }

        return  "redirect:/cly/list";
    }

2.5地址映射

在这里插入图片描述

2.6测试

测试前
在这里插入图片描述
测试后
在这里插入图片描述

三、文件下载

前端

 <a href="${pageContext.request.contextPath }/cly/download?cid=${b.cid}">下载图片</a>

后端

  @RequestMapping("/download")
    public  ResponseEntity download(ClayyDto clayyDto){
        try {
            //1.点击下载传递文件的ID  通过文件的ID查询出文件的路径
            Clayy clayy = this.clayyBiz.selectByPrimaryKey(clayyDto.getCid());
            String pic = clayy.getPic();//一个数据库地址/upload/mvc

            //实际应该配置resource.properties中
            String diskPath="K:/temp/images/";//图片的存放地址
            //http://localhost:8080/upload/mvc/0516.png
            String requestPath="/upload/mvc/";//数据库保存的地址,也是我们访问的地址
            //2.通过文件的请求地址  转换成文件存放的硬盘地址
            String realPath = pic.replace(requestPath, diskPath);
            String fileName = realPath.substring(realPath.lastIndexOf("/") + 1);
            //3.将硬盘中文件下载下来-》固定代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

        }catch (Exception e){
            e.printStackTrace();
        }

        return  null;
    }

测试结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>