0

我正在从具有以下功能的目录中读取文件:

CREATE OR REPLACE FUNCTION loadBlobFromFile(p_file_name VARCHAR2) RETURN BLOB AS
  dest_loc  BLOB := empty_blob();
  src_loc   BFILE := BFILENAME('TMT', p_file_name);
BEGIN
  -- Open source binary file from OS
  DBMS_LOB.OPEN(src_loc, DBMS_LOB.LOB_READONLY);

  -- Create temporary LOB object
  DBMS_LOB.CREATETEMPORARY(
        lob_loc => dest_loc
      , cache   => true
      , dur     => dbms_lob.session
  );

  -- Open temporary lob
  DBMS_LOB.OPEN(dest_loc, DBMS_LOB.LOB_READWRITE);


    -- Load binary file into temporary LOB
    DBMS_LOB.LOADFROMFILE(
        dest_lob => dest_loc
      , src_lob  => src_loc
      , amount   => DBMS_LOB.getLength(src_loc));

  exception 
    when DBMS_LOB.operation_failed
    then
     return empty_blob();


 -- Close lob objects
  DBMS_LOB.CLOSE(dest_loc);
  DBMS_LOB.CLOSE(src_loc);

   -- Return temporary LOB object
  RETURN dest_loc;

END loadBlobFromFile;
/

我用

select loadBlobFromFile('TESTl.doc') from dual;

当文件存在于目录中时,我得到文件。当文件不存在时,我得到空的 Blob。

现在还有最后一个问题。当文件的大小为 0 字节时,我得到一个错误。

当 dbms_lob.open 失败时,有人可以帮助我改进函数并返回一个 empty_blob() 吗?

非常感谢您!

4

2 回答 2

0

我找到了解决方案。这是我在http://www.toadworld.com/KNOWLEDGE/KnowledgeXpertforOracle/tabid/648/TopicID/DLP1/Default.aspx帮助下的最终代码

函数代码:

    CREATE OR REPLACE FUNCTION loadBlobFromFile(p_file_name VARCHAR2) RETURN BLOB AS
  dest_loc  BLOB := empty_blob();
  src_loc   BFILE := BFILENAME('Directoryname', p_file_name);
BEGIN
  BEGIN

    -- Open source binary file from OS
    DBMS_LOB.OPEN(src_loc, DBMS_LOB.LOB_READONLY);

    -- Create temporary LOB object
    DBMS_LOB.CREATETEMPORARY(
          lob_loc => dest_loc
        , cache   => true
        , dur     => dbms_lob.session
    );

    -- Open temporary lob
    DBMS_LOB.OPEN(dest_loc, DBMS_LOB.LOB_READWRITE);


    -- Load binary file into temporary LOB
    DBMS_LOB.LOADFROMFILE(
        dest_lob => dest_loc
      , src_lob  => src_loc
      , amount   => DBMS_LOB.getLength(src_loc));


   exception 
    when DBMS_LOB.operation_failed --Wenn die Datei nicht vorhanden ist
    then
      DBMS_LOB.CLOSE(src_loc);
       return empty_blob();
    when DBMS_LOB.INVALID_ARGVAL  --Wenn die Datei 0 KB gross ist.
    then
      DBMS_LOB.CLOSE(dest_loc);
  DBMS_LOB.CLOSE(src_loc);
       return empty_blob();
  END;

 -- Close lob objects
  DBMS_LOB.CLOSE(dest_loc);
  DBMS_LOB.CLOSE(src_loc);

     -- Return temporary LOB object
  RETURN dest_loc;

END loadBlobFromFile;
/

调用函数:

select loadBlobFromFile('test.doc') from dual;

问候

于 2012-11-29T08:00:59.477 回答
0

添加这样的异常。

  -- Open temporary lob
  DBMS_LOB.OPEN(dest_loc, DBMS_LOB.LOB_READWRITE);

  begin
    -- Load binary file into temporary LOB
    DBMS_LOB.LOADFROMFILE(
        dest_lob => dest_loc
      , src_lob  => src_loc
      , amount   => DBMS_LOB.getLength(src_loc));

  exception 
    when dbms_lob.operation_failed
    then
      return empty_blob();
  end;
..rest of your code.
于 2012-11-28T15:13:40.360 回答