从服务器上下载excel

来源:互联网 发布:日语语法书推荐 知乎 编辑:程序博客网 时间:2024/05/19 23:10
    /**下载trs文件*/
    public Object downloadtrsfile(final Integer id, final HttpServletResponse response) {
        return getHibernateTemplate().execute(new HibernateCallback<Integer>(){
            @Override
            public Integer doInHibernate(Session session)
                    throws HibernateException, SQLException {
                BufferedOutputStream output = null;   
                BufferedInputStream input = null;   
                try {
                ServletOutputStream ops;
                ops = response.getOutputStream();
                String SQL="select FILE_NAME,TYPE,contractFile from  TRS_FILES where id=:id";
                Query q = session.createSQLQuery(SQL).setParameter("id", id);
                List<?> t=q.list();
                Object object=t.size()>0?t.get(0):null;
                if(object!=null){
                    boolean isInline = true; //  是否允许直接在浏览器内打开(如果浏览器能够预览此文件内容,   
                    String inlineType = isInline ? "inline" : "attachment"; //  是否内联附件   
                    System.out.println(inlineType);
                    Object[] obs=(Object[]) object;
                    String name=(String) obs[0];
                    if(name==null||name.isEmpty()){
                        name="unname";
                    }
                    String downFileName = new String(name.getBytes("GBK"),"iso8859-1");
                     response.setHeader("Content-Disposition", inlineType+";filename=\""+downFileName+"\"");                       
                    String type=(String) obs[1];
                    response.setContentType(type);
                    Object o=obs[2];
                    Blob blob=(Blob)o;
                    InputStream bs = blob.getBinaryStream();
                    byte[] buffer = new byte[4096]; //  缓冲区    
                    output = new BufferedOutputStream(ops);   
                    input = new BufferedInputStream(bs);   
                    int n = (-1);   
                    while ((n = input.read(buffer, 0, 4096)) > -1) {   
                        output.write(buffer, 0, n);   
                    }  
                    output.flush();
                }
            }catch (Exception e) {    
            }
            finally{
                try {
                    output.close();
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    });
    }
原创粉丝点击