Springboot+MybatisPlus实现从数据库保存的路径下载文件(2)

还是用上次文件上传的数据库测试

 文件上传:

Springboot+MybatisPlus实现文件上传到服务器并保存路径到数据库(1)_HackAzrael的专栏-CSDN博客首先建立测试用的数据库CREATE TABLE `file` ( `id` bigint NOT NULL COMMENT '主键', `filename` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件名', `filepath` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULThttps://blog.csdn.net/HackAzrael/article/details/120984636

pom依赖

<dependencies>
        <!--springboot整合web项目-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--mybatis plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
    </dependencies>

配置文件(application.yml)

mybatis-plus:
    mapper-locations: classpath:mybatis/mapper/*Mapper.xml
    configuration:
      log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
spring:
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: root
        url: jdbc:mysql://localhost:3306/fileupload?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai
        username: root

刚才引入了Mybatis-plus和其代码生成器的依赖,现在要来生成代码

Mybatis-plus 代码生成器使用:

Mybatis Plus 代码生成器_HackAzrael的专栏-CSDN博客https://blog.csdn.net/HackAzrael/article/details/120984912

Controller

注意:这里是根据数据库中的文件id去下载文件

package com.filedownload.controller;


import com.filedownload.entity.File;
import com.filedownload.service.FileService;
import com.filedownload.util.FileDownloadUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件下载控制层
 *
 * @author az
 * @since 2021-10-30
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService fileService;


    @ApiOperation("文件下载")
    @ApiResponses({
            @ApiResponse(code = 200,message = "下载成功"),
            @ApiResponse(code = 510,message = "下载失败"),
    })
    @ApiImplicitParam(name = "id",value = "文件主键id",dataType = "int",
            example = "902727344566087680",required = true)
    @GetMapping("/fileDownload")
    public @ResponseBody
    Map<String, Object> fileDownload(final HttpServletResponse response, long id)throws Exception{
        Map<String,Object> map = new HashMap<>();
        //通过Mybatis-plus自带的方法根据id查询文件详情
        File file = fileService.getById(id);
        //获取文件路径
        String filePath = file.getFilepath();
        //获取文件名
        String fileName = file.getFilename();
        FileDownloadUtils downloadUtils = new FileDownloadUtils();
        boolean res = downloadUtils.download(response, filePath, fileName);
        if (res) {
            map.put("code",200);
            map.put("success",true);
            map.put("message","下载成功!");
        }else {
            map.put("code",510);
            map.put("success",false);
            map.put("message","下载失败!");
        }
        return map;
    }

}

因为只使用了Mybatis-plus自带的方法查询,这里的业务层、业务层实现类和数据层就不做展示了

FileDownloadUtils

注意:这里的fileName是从数据库中查到的fileName,也就是带前后缀名的文件名

/**
 * @author Az
 * @Description TODO 文件下载工具类
 * @date 2021-10-30
 */
public class FileDownloadUtils {

    public boolean download(final HttpServletResponse response,
                            String filePath,
                            String fileName) throws Exception{
        //获得文件
        File file = new File(filePath);

        //清空缓冲区,状态码和响应头(header)
        response.reset();
        //设置ContentType,响应内容为二进制数据流,文件内容编码为UTF-8
        response.setContentType("application/octet-stream;charset=utf8");
        //设置默认的文件名并设置文件名的编码
        response.setHeader("Content-Disposition","attachment;fileName="+ fileName +";filename*=utf-8''"+ URLEncoder.encode(fileName,"utf-8"));

        //文件下载
        byte[] buffer = new byte[10240];
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            //获取字节流
            OutputStream outputStream = response.getOutputStream();
            int i = bufferedInputStream.read(buffer);
            while (i != -1){
                outputStream.write(buffer, 0, i);
                i = bufferedInputStream.read(buffer);
            }
            return true;
        }catch (Exception e){
            return false;
        }finally {
            if (bufferedInputStream != null){
                try {
                    bufferedInputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

然后我们用Postman去测试接口是否可以正常使用

 这里其实是可以正常显示的,我们点击右边的Save Response->Save to a file保存为文件就可以了

这里的文件名是我们在工具类中设置过的默认文件名

测试可用,结束!

Guess you like

Origin blog.csdn.net/HackAzrael/article/details/121058334