春季启动 - 在获取请求中从文件系统抓取文件
问题描述:
我想从文件系统中抓取文件(在本例中为图像)并显示它。我可以从资源子目录中完成,但是当我尝试去文件系统时,它给了我一个FileNotFound异常。春季启动 - 在获取请求中从文件系统抓取文件
java.io.FileNotFoundException:文件:\ Y:\凯文\下载\ pic_mountain.jpg(文件名,目录名或卷标语法不正确)
我所有的代码的其余部分是香草春天从Initialize生成的启动。谢谢。
@RestController
public class ImageProducerController {
@GetMapping("/get-text")
public @ResponseBody String getText() {
return "Hello World";
}
@GetMapping(value = "/get-jpg", produces = MediaType.IMAGE_JPEG_VALUE)
public void getImage(HttpServletResponse response) throws IOException {
FileSystemResource imgFile = new FileSystemResource("file:///Y:/Kevin/downloads/pic_mountain.jpg");
// ClassPathResource imgFile = new ClassPathResource("images/pic_mountain.jpg");
System.out.println(imgFile.getURL());
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());
}
}
答
从docs:
public FileSystemResource(String path)
Create a new FileSystemResource from a file path
构造预计URL的路径部分,所以在你的情况下,只有Y:/Kevin/downloads/pic_mountain.jpg
,所以你应该尽量使用这种方式:
FileSystemResource imgFile = new FileSystemResource("Y:/Kevin/downloads/pic_mountain.jpg");
Btw。它可能是,你想念你的道路上的“用户”? - >Y:/Users/Kevin/downloads/pic_mountain.jpg
+0
谢谢!这工作。我看到的所有例子都有“file:”部分。现在我可以停止将我的头靠在墙上。 – kjbeamer
为什么要访问这样的文件系统? –
你确实意识到这段代码永远不会在你的PC之外运行,对吧? –