【发布时间】:2017-11-07 18:50:21
【问题描述】:
我正在尝试使用 ServletContext 返回图像,但出现 500 错误并且控制台显示:
java.lang.NullPointerException: null 在 org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2146) 在 org.apache.commons.io.IOUtils.copy(IOUtils.java:2102) 在 org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2123) 在 org.apache.commons.io.IOUtils.copy(IOUtils.java:2078) 在 org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:721)
配置:
@Configuration
public class ImageConfiguration {
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
}
服务:
@Service
public class ImageService {
@Autowired
ServletContext servletContext;
public byte[] getRankImage (String id) throws IOException {
byte[] b;
InputStream in;
if (id.equals("0")) {
in = servletContext.getResourceAsStream("images/level-0.png");
return IOUtils.toByteArray(in);
宁静的服务:
@RequestMapping(value = "/level/{id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(@PathVariable("id") String id) {
byte[] imageBytes;
try {
imageBytes = imageService.getRankImage(id);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(imageBytes);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
图像位于resources -> images -> {image_name},当我查看war 文件时,我确认它们在其中。我不确定我是否做错了,或者我需要以不同的方式处理路径。
---------更新1-------
【问题讨论】:
-
那么,
InputStream实例in在这里为空?
标签: spring-boot