今天介绍下SpringMvc加载本地文件的方法,我这个例子是加载“D:/uploadfile”路径下的本地图片
因为项目可能部署在不同的服务器上,为了方便我把本地的路径写在了配置文件中,然后就是在本地没有加载的文件的时候,默认加载nophoto.jpg这个文件
- 配置文件
在Springmvc的配置文件中加载这个文件
<!--读取文件 -->
<context:property-placeholder location="classpath:file.properties"/>
- Controller代码
@RequestMapping("/picShow")
public void picShow(HttpServletRequest request,HttpServletResponse response,String picName) throws IOException {
String imagePath = basePath+picName;
response.reset();
//判断文件是否存在
File file = new File(imagePath);
if (!file.exists()) {
imagePath = basePath+nophoto;
}
// 得到输出流
OutputStream output = response.getOutputStream();
if (imagePath.toLowerCase().endsWith(".jpg"))// 使用编码处理文件流的情况:
{
response.setContentType("image/jpeg;charset=GB2312");// 设定输出的类型
// 得到图片的真实路径
// 得到图片的文件流
InputStream imageIn = new FileInputStream(new File(imagePath));
// 得到输入的编码器,将文件流进行jpg格式编码
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn);
// 得到编码后的图片对象
BufferedImage image = decoder.decodeAsBufferedImage();
// 得到输出的编码器
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(image);// 对图片进行输出编码
imageIn.close();// 关闭文件流
}
output.close();
}
- jsp代码
<img class="img-responsive" src="${pageContext.request.contextPath}/info/picShow?picName=${info.user_file }">
picName是我的文件名