首页 > 解决方案 > 从 Web 应用程序在 Spring 控制器中下载纯文本文件的问题

问题描述

我遇到了一个问题,我试图在 spring 控制器方法中下载一个简单的“text/plain”文件。运行应用程序时,我在 Web 工具响应中得到了我想要的文本,即“测试”。Web 开发者工具中的响应头如下:

长度为 4,因为这是文本“test”的字节数。在控制器中,我生成了 = MediaType.TEXT_PLAIN_VALUE。但是,当我单击应用程序中的相关按钮下载文件时,不是在 Web 浏览器中显示下载,而是下载到磁盘,因为 file.txt 实际上显示在我的项目的 intellij 工作区中(我'正在用于我的 IDE)。所以,我的问题是如何在网络浏览器中进行下载,这意味着当您单击以下链接https://howtodoinjava.com/spring-mvc/spring-上的“下载源代码”按钮时会发生什么mvc-download-file-controller-example/,而不是将文件下载到我的工作区/磁盘?

支持方法/类如下所示:

public class TextFileExporter implements FileExporter {
   @Override
   public Path export(String content, String filename) {
      Path filepath = Paths.get(filename);
      Path exportedFilePath = Files.write(filepath, content.getBytes(), 
        StandardOpenOption.CREATE);
   }
}

public interface FileExporter {
   public Path export(String content, String filename);
}

手头的控制器如下:

@GetMapping(value="downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
   String filename = "example.txt";
   String content = "test";
   Path exportedpath = fileExporter.export(content, filename);
   response.setContentType(MediaType.TEXT_PLAIN_VALUE);
   Files.copy(exportedpath, response.getOutputStream());
   response.getOutputStream.flush();

}

标签: javaspringservletscontroller

解决方案


尝试直接使用 Response 实体返回 InputStreamResource

@RequestMapping("/downloadFile")
        public ResponseEntity<InputStreamResource> downloadFile() throws FileNotFoundException {
            String filename = "example.txt";
            String content = "test";
            Path exportedpath = fileExporter.export(content, filename);
            
            // Download file with InputStreamResource
            File exportedFile = exportedPath.toFile();
            FileInputStream fileInputStream = new FileInputStream(exportedFile);
            InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
                    .contentType(MediaType.TEXT_PLAIN)
                    .contentLength(exportedFile.length())
                    .body(inputStreamResource);
    }

正如@chrylis -cautiouslyoptimistic 所说,尽量避免使用低级对象,让它由 Spring 自己处理


推荐阅读