java - 从 Web 应用程序在 Spring 控制器中下载纯文本文件的问题
问题描述
我遇到了一个问题,我试图在 spring 控制器方法中下载一个简单的“text/plain”文件。运行应用程序时,我在 Web 工具响应中得到了我想要的文本,即“测试”。Web 开发者工具中的响应头如下:
- 内容配置:附件;文件名=文件.txt
- 内容类型:文本/纯文本
- 内容长度:4
长度为 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();
}
解决方案
尝试直接使用 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 自己处理
推荐阅读
- c++ - 在 C++ 中自动选择模板的类型名
- c++ - 如何将文本附加到 Qt 中的文本文件?
- python - TensorFlow XOR NN 评估函数错误
- matlab - Matlab的“复杂”功能有什么意义?
- google-sheets - 如何使用条件比较两行之间的值
- java - java.lang.OutOfMemoryError 即使使用 setFetchSize
- javascript - 从现有 JSON 数组的嵌套键/值创建一个新的 JSON 数组
- python - 在 Python 中的类和对象方面需要帮助
- ruby - Ruby 中的语法检查命令似乎没有做任何事情
- php - 部署者 - 从 git 服务器部署到同一主机(本地主机)