ssm框架下使用请求图片资源后缀消失处理

在sping mvc中使用get方法获取图片第一次光荣牺牲。。。好吧,在sping中如果路径带“.”的话会被忽略。

第二次使用了使用Spring正则表达式(SpEL)完美解决问题。

@RequestMapping(value = "/getImage/{fileName:.+}",method = RequestMethod.GET)
    public void testpic(HttpServletResponse response,@PathVariable String fileName) throws IOException {
        FileInputStream fis = null;
        File file = new File(photoLocationPath + "/" + fileName);
        fis = new FileInputStream(file);
        String fileExtensionName = "image/" + fileName.substring(fileName.lastIndexOf(".") + 1);
        //设置返回的文件类型
        response.setContentType(fileExtensionName);
        IOUtils.copy(fis, response.getOutputStream());
    }

本以为问题就此结束,结果遇上了gif的图片格式,悲催。。。。404刷一波,其他图片文件都可以,就这不行,好吧下面开动歪脑筋~

@RequestMapping(value = "/getImage/{fileName}/{suffix}",method = RequestMethod.GET)
    public void testpic(HttpServletResponse response,@PathVariable String fileName,@PathVariable String suffix) throws IOException {
        FileInputStream fis = null;
        File file = new File(photoLocationPath + "/" + fileName);
        fis = new FileInputStream(file);
        String fileExtensionName = "image/" + suffix;
        //设置返回的文件类型
        response.setContentType(fileExtensionName);
        IOUtils.copy(fis, response.getOutputStream());
    }
}

大家可以看到,我这里多传了个“suffix”指的是文件的后缀(我不会告诉你我是想把下面设置文件类型截取字符串的方法给去掉才这么做的)。可以看到下图的fileName就可以正常取值了。

当然我们也可以通过在sping mvc的配置过滤:例

<servlet-mapping> 
<servlet-name>default</servlet-name> 
<url-pattern>*.css</url-pattern> 
</servlet-mapping> 

<servlet-mapping> 
<servlet-name>default</servlet-name> 
<url-pattern>*.gif</url-pattern> 
</servlet-mapping> 

一个个去配置的话显然对不起我的名字,嗯,这里就歪到底不改了。

猜你喜欢

转载自www.cnblogs.com/nowl/p/9225629.html