java读取Blob文件显示在jsp界面

实现原理:将Blob读取为文件保存到服务器的UpLoadFile文件夹中,然后在jsp界面调用对应路径即可显示。

jsp界面代码,包含一些链接数据库的代码,大家如果用到可以将其修改为自己链接数据库的代码,其中ReadBlobFile为读取Blob的类文件

 

<%@ page language="java"
 import="java.util.*,com.rm.map.Escape,com.rm.wtems.entity.YwDevices,com.rm.wtems.service.YwDevicesManager,com.rm.map.ReadBlobFile,
 com.rm.wtems.entity.YwDevicekinds,com.rm.wtems.service.YwDevicekindsManager,com.rm.system.util.AppCtxFactory"
 pageEncoding="utf-8"%>

<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
  String basePath2=basePath+"UpLoadFile/" ;
 String dir=application.getRealPath("/"); //为获取程序运行的绝对路径,在类中文件保存时用到
%>
<%
  String idstr = request.getParameter("idstr"); 
 String FileName ="";
 String HaveFile = "0";
  if (idstr != null && !idstr.equals("null")) {
    YwDevicekindsManager managerkind = (YwDevicekindsManager) AppCtxFactory
      .getBean("ywDevicekindsManager");
    List listkinds = managerkind
      .findYwDevicekindsById(idstr);
    for (YwDevicekinds obj : listkinds) {
       FileName =flag+UUID.randomUUID().toString() + "."+obj.getDaxiuwdlx();
       ReadBlobFile.ReadStreamToByteFile(dir,FileName, obj.getDaxiubz());
       HaveFile = "1";
     }
  }
  %>


 
  

  文件显示
  
 
 

  <%
   try {
    if (HaveFile.equals("0")) {
  %>
  
  <%
   } else {
  %>
  
  <%
   }
   } catch (Exception e) {
    System.out.println("Download File Error!");
   } finally {
   }
  %>
 

 

ReadBlobFile类文件的实现代码

 

package com.rm.map;
import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;


public class ReadBlobFile {
 /**
     * 从binaryStream中读取数据到指定文件的方法
     * @param in 即binaryStream
     * @return
     * @throws Exception
     */
    public static void ReadStreamToByteFile(String path,String fileName,Blob blobstr) throws IOException{   
     //path=path+"UpLoadFile/";
     try {
   InputStream in= blobstr.getBinaryStream();   

   //FileOutputStream fileOutputStream = new FileOutputStream(new File(path).toURI().getPath());
   FileOutputStream fileOutputStream = new FileOutputStream(new File(path+"UpLoadFile\\"+fileName).toURI().getPath());
   //buffer
   byte[] buffer = new byte[1024];
   // read
   int length = 0;
   while ((length = in.read(buffer)) > 0) {
       //write
       fileOutputStream.write(buffer, 0, length);
   }
   
   fileOutputStream.flush();
   in.close();
   fileOutputStream.close();
     } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();  
     } catch (FileNotFoundException e) {
         e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
       }
  
      }
}

 

你可能感兴趣的:(java读取Blob文件显示在jsp界面)