我正在努力让HttpServletResponse response进入Spring Boot的REST控制器。其背后的目的是我想要从REST控制器返回一个文件流。
下面是代码。
@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);
}
}
}既没有下载文件,也没有抛出错误。请帮忙提个建议。谢谢。
发布于 2017-05-12 17:04:56
试一试。我明白你想做什么了吗?
@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;
}
}
}发布于 2017-08-24 18:12:40
我认为应该是这样的。
public ResponseEntity<FileSystemResource> download(@RequestBody FileDownload fileDownload, HttpServletResponse response) throws IOException { ... }Spring将为您设置响应对象。您试图做的是注入bean "HttpServletResponse“,这没有多大意义,因为它不是一个bean。
发布于 2021-02-15 23:43:18
您可以简单地以任意顺序将HttpServletResponse声明为下载方法的参数,即
public void download(Object fileObject, HttpServletResponse response) {或者,对于您的特定需求,您可以直接参考OutputStream,即
public void download(Object fileObject, OutputStream out) {在使用这两种方法中的任何一种时,都应该使用void作为方法的返回类型
或者,另一个值得一看的替代方案是使用StreamingResponseBody
https://stackoverflow.com/questions/43932163
复制相似问题