Reputation: 33
@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;
}
The image is located in src/main/webapp/resources/img folder,
stored file path is like "/img/xxx.png"
i have no idea what to do Stack trace :
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)
Upvotes: 1
Views: 645
Reputation: 78
Spring’s Resource interface is meant to be a more capable interface for abstracting access to low-level resources.
You should inject/autowire a ResourceLoader and use it to obtain the resource. All application contexts implement the ResourceLoader interface, and therefore all application contexts may be used to obtain Resource instances.
For example:
@Autowired
private ResourceLoader context;
And then:
Resource image = context.getResource(i.getFilepath_img());
InputStream is = image.getInputStream();
...
This will enable you to specify the file path as URL, file or classpath resource, or let if depend on the underlying ApplicationContext. See Table 8.1 Resource Strings for more information.
Upvotes: 0
Reputation: 4106
webapp/resources/..
is not in the classpath. You could solve this by using a ServletContext
Inject it:
@Autowired
private ServletContext servletContext;
Then get the InputStream
:
InputStream in = servletContext.getResourceAsStream(i.getFilepath_img());
This code assumes that:
getFilepath_img()
returns an absolute path relatives to your webapp context, eg. /resources/img/xxx.png
. If not, you should prepend the path eg. "/resources/" + i.getFilepath_img()
with or without the resources tailing /
Upvotes: 2