@RequestMapping(value = "/all", method = RequestMethod.GET)
public ResponseEntity<List<ItemVO>> listAll() {
ResponseEntity<List<ItemVO>> entity = null;
try {
List<ItemVO> list=service.listAll();
for(ItemVO i : list){
InputStream in = getClass().getClassLoader().getResourceAsStream(i.getFilepath_img());
i.setByte_img(IOUtils.toByteArray(in));
}
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
entity = new ResponseEntity<List<ItemVO>>(list, HttpStatus.OK);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
entity = new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return entity;
}
话音
public class ItemVO{
private int item_id;
private String filepath_img;
private byte[] byte_img;
}
图像位于 src/main/webapp/resources/img 文件夹中,
存储的文件路径类似于“/img/xxx.png”
我不知道该怎么办 堆栈跟踪:
java.lang.NullPointerException
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2146)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:2102)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2123)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:2078)
at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:721)
最佳答案
webapp/resources/..
不在类路径中。您可以使用ServletContext
来解决这个问题
注入(inject):
@Autowired
private ServletContext servletContext;
然后获取InputStream
:
InputStream in = servletContext.getResourceAsStream(i.getFilepath_img());
此代码假设:
getFilepath_img()
返回相对于您的 web 应用程序上下文的绝对路径,例如。/resources/img/xxx.png
。如果没有,您应该在前面添加路径,例如。"/resources/"+ i.getFilepath_img()
带或不带资源尾部/
关于java - getResourceAsStream 返回空指针异常(spring 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514725/