我正在努力将 HttpServletResponse 响应
放入 Spring Boot 的 REST Controller 中。背后的目的是我想从 REST Controller 返回一个文件流。
这是代码。
@Component
@Api(value = "/api/1/download", description = "act upon selected file.")
@Path("/api/1/download")
@Consumes(MediaType.APPLICATION_JSON)
@RestController
public class DownloadResource {
private final Logger log = LoggerFactory.getLogger(DownloadResource.class);
@Autowired
HttpServletResponse response;
@ApiOperation(value = "Download a selected file", notes = "allows to download a selected file")
@Path("/downloadFile")
@POST
@Autowired
public void download(Object fileObject) {
String name = (String) ((LinkedHashMap) fileObject).get("path");
response.setContentType("text/plain");
response.addHeader("Content-Disposition", "attachment; filename=abcd.txt");
try
{
Files.copy(Paths.get(name), response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
文件既没有下载也没有抛出错误。请帮忙建议。谢谢。
最佳答案
试一试。我明白你想做什么吗?
@SpringBootApplication
@RestController
public class FiledownloadApplication {
public static void main(String[] args) {
SpringApplication.run(FiledownloadApplication.class, args);
}
@PostMapping("/downloadFile")
public ResponseEntity<FileSystemResource> download(@RequestBody FileDownload fileDownload) throws IOException {
String path = fileDownload.getPath();
FileSystemResource fileSystemResource = new FileSystemResource(path);
return new ResponseEntity<>(fileSystemResource, HttpStatus.OK);
}
class FileDownload {
String path;
public FileDownload() {
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
}
关于java - 如何将 HttpServletResponse 响应获取到 Spring Boot 的 REST Controller 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43932163/