实现用struts2流信息获得图片

 

我们试着这样写:

<img src="showImag.do?imagePath=01.jpg">

可以很清楚的看到,我们试图从指定的Action中获取一张图片。这个问题的关键是在后台该如何写。

先看Action的代码:

public class ShowImgAction extends BaseAction {

    // 图片相对路径
    protected String imagePath = null;

    public String showImg() {
        // 默认的导向页面
        String strForward = FORWARD_SUCCESS;// 默认导向
        // 返回函数值
        return strForward;
    }

    /**
     * @描述:读取图片输入流
     * @开发人员:moshco zhu
     * @开发时间:2011-5-24 上午10:28:35
     * @return
     * @throws FileNotFoundException
     */
    public InputStream getDownloadFile()
            throws FileNotFoundException {
        // 文件输出流 
        BufferedInputStream bis = null;
        try {
            if (imagePath == null
                    || imagePath.trim().length() <= 0) {
                return null;
            }

            // 读取图片
            String strImgRooPath = "E:/images";
            String strImgPath = strImgRooPath + "/"
                    + imagePath;
            File fl = new File(strImgPath);
            if (!fl.exists()) {
                return null;
            }

            // 读取生成的图片
            FileInputStream fis = new FileInputStream(fl);
            bis = new BufferedInputStream(fis);

        } catch (Throwable t) {
            t.printStackTrace();
        }
        // 返回函数值
        return bis;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

}

这里面最重要的是getDownloadFile()方法,他返回的一个输出流。

然后,我们看看最重要的struts.xml里面是怎么写的:

        <!-- 显示图片Action -->
        <action name="showImg" class="Action.Common.ShowImg" method="method">
            <result type="stream">
                <param name="contentType">image/gif</param>
                <param name="inputName">downloadFile</param>
                <param name="bufferSize">4096</param>
            </result>
        </action>

这个result的类型是stream。里面参数的意思分别是:文件类型、获取流的方法、缓冲区字节。

 

就是这样,就能从后台取出想要的图片了。

 

注:1、代码里面的BaseAction是项目框架中自定义的一个类,不是struts2类库中的。大家可以继承ActionSupport就行了。

  2、关于文件类型描述,可以在Tomcat/conf/web.xml中520行左右的类型说明中找到!

 

 

 

posted @ 2012-12-03 12:12  轩辕李  阅读(2181)  评论(1编辑  收藏  举报