在Spring-MVC中从src / main / resources / ..读取资源

问题描述

我有一个使我头痛的问题。 首先,我的项目结构如下所示。

enter image description here

我做了一个控制器,该控制器将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);
    }
}

您应该包括堆栈跟踪和异常消息,这可能有助于理解您的第二个查询,但是我将检查文件是否确实存在,并使用您使用的确切名称。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...