---
title: "img标签动态请求图片"
author: "wangcheng"
date: "2007-11-15T14:33:47Z"
tags: ["HTML", "Struts", "XML", "浏览器"]
slug: "img"
draft: false
lastmod: "2007-11-15T14:33:47Z"
id: 140878
url: "https://wangcheng.iteye.com/blog/140878"
---

html的img标签是很常见的，一般的应用是

xml 代码

 

1. &lt;img src="/images/abc.jpg"/&gt;

等形式。

其实浏览器在解析html时，遇到img标签后会单独请求src里指定的url。  
这样就可以简单的使用img标签来动态加载图片了。

测试程序基于struts，先来写个action

java 代码

 

01. public ActionForward image(ActionMapping mapping, ActionForm form,
02. HttpServletRequest request, HttpServletResponse response)
03. throws Exception {
04. File file= new File(request.getSession().getServletContext().getRealPath("/images/abc.jpg"));
05. if(file.exists()) {
06. response.setContentType("image/jpeg");
07. ServletOutputStream sos = response.getOutputStream();
08. IOUtils.copy(new FileInputStream(file), sos);
09. sos.flush();
10. sos.close();
11. }
12. return null;
13. }

struts-config.xml的配置也很简单，这里就不写了。

最后就是写个html文件，里面只写一句就可以了

xml 代码

 

1. &lt;img src="image.do?method=image"/&gt;