在项目中,因为业务需要,用户上传的图片存放在服务器的D盘中,为了读取并显示到页面上,尝试了两种方法:
一 通过流读取
java代码:
@RequestMapping(value = "/seekExperts")
@ResponseBody
public String createFolw(HttpServletRequest request,
HttpServletResponse response, Model model) {
// response.setContentType("image/*");
PageData pd = new PageData();
pd = this.getPageData();
//取路径
String path = pd.getString("path");
FileInputStream fis = null;
OutputStream os = null;
try {
fis = new FileInputStream(path);
os = response.getOutputStream();
int count = 0;
byte[] buffer = new byte[1024 * 8];
while ((count = fis.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
fis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
前台代码:
<img alt="image" id="myImage" style="height:250px;width:400px;" src="defectivemanage/seekExperts.do?path=${var.PATH }"/>
二 通过配置虚拟目录读取
打开tomcat的conf文件夹,在server.xml中的<Host></Host>标签内加入
<Context path="/dataResourceImages" docBase="D:\a" crossContext="true" reloadable="false" debug="0"/>
jsp代码:
<img alt="image" id="myImage" style="height:250px;width:400px;" src="/dataResourceImages/GIF1.gif"/>
修改后重启,就可以看到图片啦