首页 > 代码库 > 读取MySQL存储二进制的语音、图片(Blob类型)

读取MySQL存储二进制的语音、图片(Blob类型)

/**   * 下载语音   * Remarks:   * @throws Exception   */

 public void downloadYuyin() throws Exception {   

String voiceId = getRequest().getParameter("voiceId");  

 InputStream inputStream = voiceService.findInputByVoiceId(voiceId);  

 String realPath1 = getRequest().getRealPath("/") + "/upload/voice.pttly";  

 File f2 = new File(realPath1);   FileOutputStream dos = new FileOutputStream(f2);  // 生成带缓冲区的二进制 写入流 

 OutputStream dosss = new DataOutputStream(new BufferedOutputStream(  new FileOutputStream(f2)));

  // 创建文件读取缓冲区 

byte[] buf = new byte[2048]; 

// 读进 缓冲区    dos.write(toByteArray(inputStream));

// 把文件数据写入文件     

dos.close();//关闭流            

String realPath = getRequest().getRealPath("/") + "/upload/voice.pttly";   

File file = new File(realPath);  

 String filename = file.getName();

  InputStream fis = new BufferedInputStream(new FileInputStream(     realPath));

  byte[] buffer = new byte[fis.available()];   fis.read(buffer);   fis.close();   // 清空

response   getResponse().reset();  

 // 设置response的Header   

getResponse().addHeader("Content-Disposition", "attachment;

filename="+ new String(filename.getBytes()));  

 //getResponse().addHeader("Content-Disposition", "attachment;filename="+"yuyin.pttly");   

getResponse().addHeader("Content-Length", "" + file.length());  

 OutputStream toClient = new BufferedOutputStream(getResponse()     .getOutputStream());  

 getResponse().setContentType("application/octet-stream");  

 toClient.write(buffer);  

 toClient.flush();  

 toClient.close();

 }  

 

 

 

 

//service

public InputStream findInputByVoiceId(String voiceId) {
  return voiceDao.findInputByVoiceId(voiceId);
 }

 

 

 

//dao

@SuppressWarnings("rawtypes")
 public InputStream findInputByVoiceId(String voiceId) {
  String sql = "SELECT voice_id,call_user_id,group_id,UnitId,participate_user_id,call_type,starttime,endtime,voicedata FROM Voice_Info WHERE voice_id="+voiceId;
  SQLQuery sqlQuery = createSQLQuery(sql.toString());
  List lists = sqlQuery.list();
  InputStream input = null;
  for(int i=0;i<lists.size();i++){
   Object[] objects=(Object[])lists.get(0);
   if(objects != null){
    SerializableBlob o = (SerializableBlob) objects[8];
    try {
     input = o.getBinaryStream();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
  }
  return input;
 }

 

读取MySQL存储二进制的语音、图片(Blob类型)