struts2 文件以字节存数据库

1、struts2 文件以字节存数据库


 public static byte[] getByteFromFile(File file){
  if (file ==null){ 
           return null; 
       
       try{ 
           FileInputStream in = newFileInputStream(file); 
           ByteArrayOutputStream out = newByteArrayOutputStream(); 
           byte[] b = new byte[1024];
           int len; 
           while ((len = in.read(b)) != -1) 
               out.write(b, 0, len); 
               in.close(); 
               out.close(); 
           return out.toByteArray(); 
       } catch (IOException e){ 
           e.printStackTrace();
           return null;
       
    }

 

2、struts2通过文件流将图片文件显示在页面中

 http://blog.sina.com.cn/s/blog_9d05e9c101014dre.html

 

图片只是所有文件系统的一个分支,这一次我们就来讨论下图片文件的显示问题,当我们采用第一宗方式将图片文件上传到服务器的硬盘时,我们要调用文件并且显示出来,只需要告诉系统图片文件所在路径就可以了,通过连接服务器的图片所在路径就可以显示图片,在此就不多做介绍,我们来介绍另外一种方式显示图片文件。

首先,我们要知道一个图片文件在数据库中存储的是内容是什么,一般情况下是以字节数组形式存入到数据库中。

假设一个文件对象file,在数据库中有相关属性,其中内容是content,byte[] 类型

action中的代码如下

public String viewImages() {

        HttpServletResponseresponse = null;

        ServletOutputStreamout = null;
        try{
            response= ServletActionContext.getResponse();
            response.setContentType("multipart/form-data");
            out= response.getOutputStream();
            out.write(file.getContent());
            out.flush();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(out != null) {
                try{
                    out.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            
}

            if(response != null) {
                try{
                    ((OutputStream)response).close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            
}

        }
        
returnnull;
    }

注意,此方法必须放回null,

struts.xml的配置如下

 

j

struts.xml的配置如下

<action name="访问action名" class="action类名" method="viewImages"></action>

jsp页面的调用代码如下

<img alt="显示图片" src="<s:url action='访问action名'><s:param name='向action传递参数名' value='参数值'></s:param></s:url>"></img>

至此,通过struts2将图片流显示在jsp页面中,同时如果直接访问这个action可以将这个文件下载到本地磁盘中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值