struts2+hibernate+sqlserver2005图片上传以及在页面显示

来源:互联网 发布:邪眼暴君 知乎 编辑:程序博客网 时间:2024/04/28 03:29

        问题描述:

        在SSH框架下,上传图片,存储到sqlserver2005数据库中,并能够从数据库中取出来在页面展示。

        解决方法:

        1、图片上传直到action这一步请参照前一篇文章,本文从这里开始说起。首先说实体类:Map

@Entity

@Table(name = "OBJ_MAP")

public class Map extends DomainObject {

        // 其他字段略去

        @Column(name = "mapAddr", nullable = false)

        private byte[] mapAddr;    // 数据库类型为image

        public byte[] getMapAddr() {

                return mapAddr;

        }

        public void setMapAddr(byte[] mapAddr) {

                this.mapAddr = mapAddr;

        }

}

2、在service中将图片上传至数据库:

public String addMap(MapBean bean){

         Map m = new Map();

                      InputStream in = null;
                      if (StringUtils.isNotEmpty(bean.getMapAddrFileName())) {
                                 try {
                                            byte buffer[] = new byte[(int)t.getMapAddr().length()]; 
                                            in = new FileInputStream(t.getMapAddr()); 
                                            in.read(buffer); 
                                            m.setMapAddr(buffer);
                                 } catch (FileNotFoundException e) {
                                            e.printStackTrace();
                                 } catch (IOException e) {
                                            e.printStackTrace();
                                 }

                      }

        mapDao.save(m);   // mapDao由Spring注入

}

3、 存入数据库后,其他页面需要从数据库中取出该图片显示:

@Controller("mapAction")
@Scope("prototype")
public class MapAction{

        private InputStream imagStream;  

        private MapService mapService;

        public String getMap(){
                String id = request.getParameter("id");
                Map map = mapService.getMapById(id);
                if (map == null) {
                        request.setAttribute("message", "地图不存在!");
                } else {
                        imagStream = new ByteArrayInputStream(map.getMapAddr());
                }
                return "mapImag";
        }

        public InputStream getImagStream() {
                return imagStream;
        }
        public void setImagStream(InputStream imagStream) {
                this.imagStream = imagStream;
        }
        public void setMapService(MapService mapService) {
                this.mapService = mapService;
        }

}

struts.xml配置如下:

<action name="mapAction" class="mapAction">

        <result name="mapImag" type="stream">     <!-- 此处type必须是stream -->
                <param name="contentType">image/jpeg,image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param>
                <param name="inputName">imagStream</param>
        </result>

</action>

JSP中相关的地方如下:

<div id="preview_fake">
        <img id="preview" src="mapAction!getMap.action?id=<s:property value='id'/>" />
</div>


原创粉丝点击