SpringBoot文件下载-下载指定路径下的文件

下载指定路径下的文件

Controller代码

import com.thunisoft.jy.imp.utils.DownloadFileUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/api")
public class WhpxxszController {
    //文件上级目录
    String PATH = "user";
    //文件名
    String FILENAME ="user.xlsx";
    //下载展示的文件名
    String NEWNAME=""
   /**
     * 下载模板
     * @return 返回excel模板
     */
    @RequestMapping(value = "/downloadWhpModel", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "模板下载", httpMethod = "GET", produces = "application/json;charset=UTF-8")
    public Object downloadModel(){
        ResponseEntity<InputStreamResource> response = null;
        try {
            response = DownloadFileUtil.download(PATH, FILENAME, "导入模板");
        } catch (Exception e) {
            log.error("下载模板失败");
        }
        return response;
    }
}
package com.thunisoft.jy.imp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.*;
@Slf4j
public class DownloadFileUtil {

    public static final String separator = File.separator;

    /**
     * 下载样表
     * @param filePath 文件上级目录
     * @param fileName 文件名
     * @param newName  下载的展示文件名
     * @return 响应
     */
    public static ResponseEntity<InputStreamResource> download(String filePath, String fileName, String newName) {
        String route = "static" + separator + "templates" + separator;
        String path = null;
        ResponseEntity<InputStreamResource> response = null;
        try {
            path = route + filePath + separator + fileName;
            ClassPathResource classPathResource = new ClassPathResource(path);
            InputStream inputStream = classPathResource.getInputStream();
            //File file = new File(path);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "attachment; filename="
                            + new String(newName.getBytes("gbk"), "iso8859-1") + ".xlsx");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            response = ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {
            log.error("找不到指定的文件", e1);
        } catch (IOException e) {
            log.error("获取不到文件流", e);
        }
        return response;
    }
}

以上代码中的 “static“和"templates"是文件的路径的层级

String route = "static" + separator + "templates" + separator;

以下为文件夹层级关系
在这里插入图片描述

  • 8
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
在Spring Boot中,实现文件下载到本地指定目录可以通过以下步骤实现: 1. 首先,需要引入相关的依赖项。在项目的pom.xml文件中,添加如下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 创建一个Controller类来处理文件下载请求。在这个类中,我们可以定义一个方法来实现文件下载功能。例如,我们可以使用`ResponseEntity`返回文件和响应头信息: ```java import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Path; import java.nio.file.Paths; @RestController public class FileController { private static final String DOWNLOAD_DIR = "your_download_directory_path"; @GetMapping("/download/{filename}") public ResponseEntity<Resource> downloadFile(@PathVariable String filename) { try { Path filePath = Paths.get(DOWNLOAD_DIR).resolve(filename); Resource resource = new UrlResource(filePath.toUri()); if (resource.exists() && resource.isReadable()) { return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } } catch (MalformedURLException e) { e.printStackTrace(); } return ResponseEntity.notFound().build(); } } ``` 3. 在`DOWNLOAD_DIR`中设置您要下载文件的目录路径。在上述示例中,我们使用`Paths.get(DOWNLOAD_DIR)`来获取目录路径,并使用`resolve(filename)`方法来获取文件路径。 4. 当客户端访问`/download/{filename}`路径时,`downloadFile`方法将被调用。它将检查文件是否存在和可读,并根据文件的内容类型设置响应头信息。最后,它使用`ResponseEntity`将文件作为响应返回给客户端。 5. 请注意,您还可以添加其他必要的验证和错误处理代码,以确保安全性和可靠性。 此外,确保在运行该应用程序之前,设置好正确的下载目录路径,并且权限设置正确以避免操作限制。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值