Java Can';t访问控制器中src/main/webapp/WEB-INF/resources/img中的图像文件以在jsp中显示
我尝试显示Java Can';t访问控制器中src/main/webapp/WEB-INF/resources/img中的图像文件以在jsp中显示,java,spring,spring-boot,spring-mvc,jsp,Java,Spring,Spring Boot,Spring Mvc,Jsp,我尝试显示src/main/webapp/WEB-INF/resources/img/文件夹中的图像(不同于src/main/resources) 它不工作-没有图像,但是如果我用绝对路径替换文件构造函数中的路径,如下所示:C://…/some_File.png它工作正常。你不能通过“文件”来读取图像,你需要通过ServletContext @Controller @RequestMapping("/items") public class ItemsController { @Au
src/main/webapp/WEB-INF/resources/img/
文件夹中的图像(不同于src/main/resources
)
它不工作-没有图像,但是如果我用绝对路径替换文件
构造函数中的路径,如下所示:C://…/some_File.png
它工作正常。你不能通过“文件”来读取图像,你需要通过ServletContext
@Controller
@RequestMapping("/items")
public class ItemsController {
@Autowired
ServletContext context;
@GetMapping( "/images/{itemId}")
@ResponseBody
public byte[] getItemImageById(@PathVariable long itemId) throws IOException {
BufferedImage originalImage =
ImageIO.read(context.getResourceAsStream("/WEB-INF/resources/img/" + itemId + ".png"));
// your original code
}
}
另一种对我有效的方法是:
@Autowired
ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource(
"/WEB-INF/resources/img/" + itemId + ".png");
String path = resource.getFile().getPath();
return Files.readAllBytes(Paths.get(path));
另外,您对另一种方法(第二个答案)有何看法?ResourceLoader将是一个ServletContextResourceLoader,并且执行与手动操作完全相同的操作:使用servletcontext获取资源。至于转换为文件:这将适用于扩展的war.files,但不适用于未扩展的war.files,而且这是一个不必要的步骤,因为您可以直接获取输入流,而无需遍历文件。
@Controller
@RequestMapping("/items")
public class ItemsController {
@Autowired
ServletContext context;
@GetMapping( "/images/{itemId}")
@ResponseBody
public byte[] getItemImageById(@PathVariable long itemId) throws IOException {
BufferedImage originalImage =
ImageIO.read(context.getResourceAsStream("/WEB-INF/resources/img/" + itemId + ".png"));
// your original code
}
}
@Autowired
ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource(
"/WEB-INF/resources/img/" + itemId + ".png");
String path = resource.getFile().getPath();
return Files.readAllBytes(Paths.get(path));