如何解决在Spring-MVC中从src / main / resources / ..读取资源
我做了一个控制器,该控制器将image(*。png)文件返回到适当的请求。
控制器的代码写在下面。
@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。如果请求参数错误,或者请求参数try-catch
的文件名不存在,我添加了noimage.png
短语来发送image_name
。但这似乎不起作用,它给我日志说
class path resource [images/stores/noima.png] cannot be opened because it does not exist
(如果您需要了解完整的堆栈跟踪信息,请在下面评论。)
第二季度。我在文件夹hello.png
中有2个图像文件noimage.png
和/resources/images/stores/
。我可以正确读取noimage.png
,但是如果发出请求localhost:8080/ImageStore.do?image_name=hello.png
,则会出错,并在Q1中进行相同的记录。
解决方法
没有理由认为该构造函数将导致一个null
值。
您可能会从getInputStream
方法中获得异常,该方法是https://github.com/mailhog/MailHog抛出
FileNotFoundException-如果基础资源不存在
IOException-如果无法打开内容流
稍作调整可能会有所帮助
@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);
}
}
您应该包括堆栈跟踪和异常消息,这可能有助于理解您的第二个查询,但是我将检查文件是否确实存在,并使用您使用的确切名称。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。