Reputation: 604
I have a question that makes my head ache.
First, my project structure looks like below.
I made a controller, which returns image(*.png) file to the appropriate request.
The code of controller is written below.
@Controller
public class ImageController {
@GetMapping(value = "/ImageStore.do", produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getStoreImage(HttpServletRequest request) throws IOException {
String image_name = request.getParameter("image_name");
Resource resource = null;
try {
resource = new ClassPathResource("/images/stores/" + image_name);
if(resource == null) {
throw new NullPointerException();
}
} catch(NullPointerException e) {
resource = new ClassPathResource("/images/stores/noimage.png");
}
InputStream inputStream = resource.getInputStream();
return IOUtils.toByteArray(inputStream);
}
}
Q1. I added try-catch
phrase to send noimage.png
if the request parameter is wrong, or if the filename of request parameter image_name
does not exist. But it doesn't seem to work, and it gives me log saying
class path resource [images/stores/noima.png] cannot be opened because it does not exist
(If you need to know the full stack trace, I will comment below.)
Q2. I have 2 image files, hello.png
and noimage.png
in the folder /resources/images/stores/
. I can read noimage.png
correctly, but if I make request localhost:8080/ImageStore.do?image_name=hello.png
, then it makes an error, making the same log in Q1.
Upvotes: 0
Views: 455
Reputation: 11818
There's no reason to think that the constructor would result in a null
value.
The exception you are getting is likely from the getInputStream
method, which is documented to throw
FileNotFoundException - if the underlying resource doesn't exist
IOException - if the content stream could not be opened
A slight adjustment might help
@Controller
public class ImageController {
@GetMapping(value = "/ImageStore.do", produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getStoreImage(HttpServletRequest request) throws IOException {
InputStream is = null;
try {
String image_name = request.getParameter("image_name");
is = new ClassPathResource("/images/stores/" + image_name).getInputStream();
} catch(FileNotFoundException e) {
is = new ClassPathResource("/images/stores/noimage.png").getInputStream();
}
return IOUtils.toByteArray(is);
}
}
You should include the stack trace, and exception message, which might assist understanding your second query, but I would check that the file really does exist, with the exact name you're using.
Upvotes: 1