我想通过Spring的REST端点提供一个.yaml文件,我知道它不能直接在浏览器中显示(这里只说Chrome ),因为它不支持yaml文件的显示。我已经包含了我认为是实现此目的所必需的库compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.9.9'。
如果我在浏览器中打开端点/v2/api-doc,它将提示我下载一个与端点/v2/api-doc完全相同的文件。它包含正确的内容。
问:有没有一种方法可以正确地传输.yaml文件,以便提示用户使用安全的myfile.yaml?
@RequestMapping(value = "/v2/api-doc", produces = "application/x-yaml")
public ResponseEntity<String> produceApiDoc() throws IOException {
byte[] fileBytes;
try (InputStream in = getClass().getResourceAsStream("/restAPI/myfile.yaml")) {
fileBytes = IOUtils.toByteArray(in);
}
if (fileBytes != null) {
String data = new String(fileBytes, StandardCharsets.UTF_8);
return new ResponseEntity<>(data, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}发布于 2019-08-22 16:10:34
您应该设置一个Content-Disposition头(我推荐使用ResourceLoader在Spring Framework中加载资源)。
示例:
@RestController
public class ApiDocResource {
private final ResourceLoader resourceLoader;
public ApiDocResource(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@GetMapping(value = "/v2/api-doc", produces = "application/x-yaml")
public ResponseEntity produceApiDoc() throws IOException {
Resource resource = resourceLoader.getResource("classpath:/restAPI/myfile.yaml");
if (resource.exists()) {
return ResponseEntity
.ok()
.contentType(MediaType.parseMediaType("application/x-yaml"))
.header("Content-Disposition", "attachment; filename=myfile.yaml")
.body(new InputStreamResource(resource.getInputStream()));
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}https://stackoverflow.com/questions/57603856
复制相似问题