JAVA将图片保存成oracle的Blob类型数据

以下是一个带Blob类型的存储过程
CREATE OR REPLACE PROCEDURE updatepicture (pi_mallid VARCHAR2,pi_tb_ord_id VARCHAR2,pi_goodsid VARCHAR2,pi_picture BLOB,
                                po_result OUT NUMBER,
                                po_message OUT VARCHAR2) IS
 v_ord_id netsale.ord_id%TYPE;
BEGIN
  SELECT MAX(ord_id) INTO v_ord_id FROM netsale
  WHERE mallid = pi_mallid AND tb_ord_id = pi_tb_ord_id ;
  UPDATE netsales
  SET picture = pi_picture
  WHERE ord_id = v_ord_id AND goodsid = pi_goodsid;
  
  IF SQL%ROWCOUNT <> 1 THEN
    po_result :=101;
    po_message := '插入图片失败';
  ELSE
    po_result := 0;
    po_message :='SUCCESS';
  END IF;
EXCEPTION WHEN OTHERS THEN
  po_result :=401;
  po_message := SQLERRM;
  RETURN;
END;


JAVA数据保存
public Map
    
    
     
      updatepicture(Map
     
     
      
       map) throws Exception {
		Map
      
      
       
        outMap = new HashMap
       
       
        
        ();
		synchronized (dao) {
			DBConnect conn = new DBConnect();
			try {
			    //获取链接部分有封装,但在该代码段中不是重点
				conn.init(null, E_DB_Name.e_db_rmsdb.value(), false);
				String po_result="";
				String po_msg="";
				String sql = "{call updatepicture(?,?,?,?,?,?)}";
				java.sql.CallableStatement ps = conn.prepareCall(sql);
				ps.setString(1, map.get("PI_MALLID")+"");
				ps.setString(2, map.get("PI_TB_ORD_ID")+"");
				ps.setString(3, map.get("PI_GOODSID")+"");
				byte[] b=(byte[])map.get("PI_PICTURE");
				InputStream is = new ByteArrayInputStream(b);
				//设置BLOB类型的值
				ps.setBinaryStream(4, is, b.length);
			    ps.registerOutParameter(5, java.sql.Types.VARCHAR);
			    ps.registerOutParameter(6, java.sql.Types.VARCHAR);
			    boolean flag=ps.execute();
			    //输出out值
				System.out.println(ps.getString(5));
				System.out.println(ps.getString(6));
			}  catch (SQLException e) {
				conn.rollback();
				e.printStackTrace();
				throw new Exception(e.getMessage());
			} catch (Exception e) {
				conn.rollback();
				e.printStackTrace();
			} finally {
				conn.close();
			}
			
		}
		return outMap;
	}
       
       
      
      
     
     
    
    


将Base64格式的图片字符串转成byte[],并执行存储过程保存
import sun.misc.BASE64Decoder;

public class Base64ToByte {
    public static void main(String[] args) throws Exception {
        String base64ImgStr="";//此为base64格式的字符串
        //判断图片的格式
        String data = "data:image";
        int sIndex = base64ImgStr.indexOf(data);
        String chanImgStr = base64ImgStr.substring(sIndex+data.length());
        int eIndex = chanImgStr.indexOf(";");
        String suffix = chanImgStr.substring(1, eIndex);
        String base = "base64,";
        int bIndex = base64ImgStr.indexOf(base);
        base64ImgStr = base64ImgStr.substring(bIndex + 7);

        BASE64Decoder decoder = new BASE64Decoder();
		byte[] imgbyte = decoder.decodeBuffer(base64ImgStr);
		Map
     
     
      
       map =new HashMap
      
      
       
       ();
		map.put("PI_MALLID", "1");
		map.put("PI_TB_ORD_ID", "12016091720000000000");
		map.put("PI_GOODSID", "74445901");
		map.put("PI_PICTURE", imgbyte);
		Map
       
       
        
         rm=new SqlTest.updatepicture(map);
		
    }
}
       
       
      
      
     
     



另外一个是通过图片url地址获取byte[],之后保存成Blob类型数据
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;        
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
        
        
public class PicUrlSaveBlob {        
		
	public Map
     
     
      
       updatepicture(Map
      
      
       
        map) throws Exception {
		Map
       
       
        
         outMap = new HashMap
        
        
         
         ();
		HttpURLConnection urlconn =null;
		InputStream inStream=null;
		InputStream is=null;
		synchronized (dao) {
			DBConnect conn = new DBConnect();
			try {
			    //获取数据链接部分有封装,但在该代码段中不是重点,请用自己方法获取数据库连接
				conn.init(null, E_DB_Name.e_db_rmsdb.value(), false);
				String po_result="";
				String po_msg="";
				String sql = "{call updatepicture(?,?,?,?,?,?)}";
				java.sql.CallableStatement ps = conn.prepareCall(sql);
				ps.setString(1, map.get("PI_MALLID")+"");
				ps.setString(2, map.get("PI_TB_ORD_ID")+"");
				ps.setString(3, map.get("PI_GOODSID")+"");
				//设置BLOB类型的值
				URL url=new URL("http://127.0.0.1/img/1.jpg");
		        urlconn = (HttpURLConnection)url.openConnection();
		        urlconn.setRequestMethod("GET");
		        urlconn.setConnectTimeout(5 * 1000);
		        inStream = urlconn.getInputStream();//通过输入流获取图片数据
		        byte[] b=inputStreamToByte(inStream);
		        is = new ByteArrayInputStream(b);
		        ps.setBinaryStream(4, is, b.length);
			    ps.registerOutParameter(5, java.sql.Types.VARCHAR);
			    ps.registerOutParameter(6, java.sql.Types.VARCHAR);
			    boolean flag=ps.execute();
			    //输出out值
				System.out.println(ps.getString(5));
				System.out.println(ps.getString(6));
			}  catch (SQLException e) {
				conn.rollback();
				e.printStackTrace();
				throw new Exception(e.getMessage());
			} catch (Exception e) {
				conn.rollback();
				e.printStackTrace();
			} finally {
				conn.close();
			}
			
		}
		return outMap;
	}
	
	public static byte[] inputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bytestream.write(ch);
		}
		byte imgdata[] = bytestream.toByteArray();
		bytestream.close();
		return imgdata;
    }
}
        
        
       
       
      
      
     
     







  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis提供了Blob类型的支持,可以将二进制数据(如图片)存储到OracleBlob字段中。 首先,在Mapper.xml中定义一个insert语句,如下所示: ``` <insert id="insertImage" parameterType="Map"> INSERT INTO image_table(id, image) VALUES(#{id}, #{image,jdbcType=BLOB}) </insert> ``` 其中,#{image,jdbcType=BLOB}表示将image属性映射到数据库的BLOB字段。 然后,在Java代码中,将图片字节数组,再将字节数组封装到一个Map中,作为参数调用insertImage方法,如下所示: ``` byte[] imageBytes = Files.readAllBytes(Paths.get("path/to/image.png")); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("id", 1); paramMap.put("image", imageBytes); mapper.insertImage(paramMap); ``` 以上代码将读取一个PNG格式的图片文件,将其字节数组,然后将字节数组封装到一个Map中,作为参数调用insertImage方法,将图片存储到数据库中。 查询Blob类型数据时,可以使用MyBatis提供的ResultHandler接口来处理Blob类型数据,如下所示: ``` public class ImageResultHandler implements ResultHandler { @Override public void handleResult(ResultContext context) { ImageEntity entity = (ImageEntity) context.getResultObject(); Blob blob = entity.getImage(); byte[] bytes = null; try (InputStream inputStream = blob.getBinaryStream()) { bytes = IOUtils.toByteArray(inputStream); } catch (SQLException | IOException e) { e.printStackTrace(); } entity.setImageBytes(bytes); } } public interface ImageMapper { @Select("SELECT id, image FROM image_table WHERE id=#{id}") @ResultType(ImageEntity.class) void getImage(long id, ResultHandler handler); } ``` 以上代码定义了一个ImageResultHandler类,实现了ResultHandler接口,用于处理查询结果中的Blob类型数据。在调用ImageMapper的getImage方法时,将ImageResultHandler实例作为参数传入,MyBatis会自动调用ImageResultHandler的handleResult方法,将查询结果封装ImageEntity实例。 在ImageEntity类中,可以定义一个byte[]类型的属性,用于存储从Blob字段中读取的字节数组。这样,查询到的图片数据就可以直接使用了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值