getResourceAsStream returns NullpointErexception(春季 4)

getResourceAsStream returns NullpointException (spring4)

@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;
}

VO

 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

来解决这个问题

注入它:

@Autowired
private ServletContext servletContext;

然后得到InputStream:

InputStream in = servletContext.getResourceAsStream(i.getFilepath_img()); 

此代码假设:

  • getFilepath_img() returns 相对于您的 webapp 上下文的绝对路径,例如。 /resources/img/xxx.png。如果没有,您应该在路径前面加上例如。 "/resources/" + i.getFilepath_img() 有或没有资源拖尾 /

Spring’s Resource接口旨在成为一个更强大的接口,用于抽象访问低级资源。

您应该 inject/autowire 一个 ResourceLoader 并使用它来获取资源。所有的application context都实现了ResourceLoader接口,因此所有的application context都可以用来获取Resource实例。

例如:

@Autowired
private ResourceLoader context;

然后:

Resource image = context.getResource(i.getFilepath_img());
InputStream is = image.getInputStream();
...

这将使您能够将文件路径指定为 URL、文件或类路径资源,或者让其依赖于底层 ApplicationContext。有关详细信息,请参阅 Table 8.1 Resource Strings