嗨大家,因为这是我的控制器类,当我在postman中运行此应用程序时,它的显示状态为200 ok.but文件无法读取如何在文件中将扩展名作为字符串参数传递?我错过了什么,你的帮助非常可观,知识渊博
@RequestMapping(value = "/file/{name}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> download(@PathVariable String name) {
try {
File inputFile = fileSystemHandler.read(name);
HttpHeaders headers = new HttpHeaders();
// headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
headers.add(HttpHeaders.CONTENT_LENGTH, "" + inputFile.length());
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename= " + name);
InputStreamResource isr = new InputStreamResource(new FileInputStream(inputFile));
return new ResponseEntity<InputStreamResource>(isr, headers, HttpStatus.OK);
} catch (Exception ex) {
// return data;
}
return null;
}
这是我的文件系统处理程序类
public File read(String name) {
File inputFile = null;
try {
inputFile = new File(env.getProperty("file.Path") + name);
return inputFile;
} catch (Exception ex) {
Logger.getLogger(FileSystemHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return inputFile;
}
答案 0 :(得分:1)
问题读起来不清楚,但我假设您正在请求类似“readme.txt”的内容,但在请求中,您在检查文件名时会得到简单的“自述”。这是因为spring尝试使用路径末尾的.txt来确定响应的内容类型。您需要停用该行为,或在请求结束时使用尾部斜杠(http://localhost:8080/file/readme.txt/)。
要在spring-boot中禁用,你可以这样做:
@Configuration
public static class MvcConfig extends EnableWebMvcConfiguration {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
super.configurePathMatch(configurer);
configurer.setUseRegisteredSuffixPatternMatch(false);
configurer.setUseSuffixPatternMatch(false);
}
}