Oracle read File from Directory with exception

前端 未结 2 1797
南笙
南笙 2021-01-16 22:57

I\'m reading files from a Directory with the following function:

CREATE OR REPLACE FUNCTION loadBlobFromFile(p_file_name VARCHAR2) RETURN BLOB AS
  dest_loc          


        
相关标签:
2条回答
  • 2021-01-16 23:21

    add an exception like this.

      -- 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.
    
    0 讨论(0)
  • 2021-01-16 23:39

    I found the resolution. Here is my final code with help from http://www.toadworld.com/KNOWLEDGE/KnowledgeXpertforOracle/tabid/648/TopicID/DLP1/Default.aspx

    The code of the function:

        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;
    /
    

    Call the function:

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

    greetz

    0 讨论(0)
提交回复
热议问题