附件上傳-入庫篇

接上一篇:http://lz726.iteye.com/blog/1882265

 

開發架構是struts+spring的。 DAO層就是用spring的jdbctemplate

大對象用了LobHandler,用這個東西問題也蠻多。

因爲附件大小沒有做限制,可能很大,所以採取流的方式。但是LobHandler 處理流的方式,網絡上都找不到例子,就算找到了,也是不能用的,頭大了。

界面上傳進來的流,不懂爲什麼不能直接用LobHandler 入庫,最後做了轉換可以實現。代碼如下:

 

		final InputStream stream=(InputStream)cform.getValue("stream");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] bytes =new byte[10240];
		int length=0;
		while ((length = stream.read(bytes)) != -1) {
			baos.write(bytes, 0, length);
		}
		baos.flush();
		final InputStream bais=new ByteArrayInputStream(baos.toByteArray());
		
		ireturn=jdbcTemplate.execute(sql.toString(),new AbstractLobCreatingPreparedStatementCallback(lobHandler){ 
	              protected void setValues(PreparedStatement pstmt,LobCreator lobCreator){  
	                 try { 
	                    	pstmt.setString(1, id);
							          lobCreator.setBlobAsBinaryStream(pstmt,7,bais,bais.available());
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	               }
	      });

 

 

配置

	<bean id="lobHandler"  class="org.springframework.jdbc.support.lob.DefaultLobHandler"  lazy-init="true"> </bean> 
 		

 

直接讀取文件的,就可以。

 

    final File file = new File("d:\\a.jpg");
		LobHandler lobHandler = new DefaultLobHandler(); 	
		final InputStream input = new FileInputStream(file);	
		final String filesize=String.valueOf(file.length());
		ireturn=jdbcTemplate.execute(sql.toString(),new AbstractLobCreatingPreparedStatementCallback(lobHandler){ 
	              protected void setValues(PreparedStatement pstmt,LobCreator lobCreator){  
	                 try { 
	                    	pstmt.setString(1, id);
							          lobCreator.setBlobAsBinaryStream(pstmt,7,input,(int)file.length());
						} catch (SQLException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
	               }
	      });

 

 

現在還不知道,在不同中間件下是否有問題,是否支持tomcat以外的,開發環境是tomcat的沒問題。

 

 

現在想來,所有問題都是可以解決的,只要是問題。相信吧~

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章