Monday, 16 November 2015

Code sample to read and upload a file in application server

SELECTION-SCREEN BEGIN OF BLOCK block01
                WITH FRAME TITLE text-001.     "File Path
PARAMETERS: p_file LIKE  rlgrap-filename OBLIGATORY ,  "INPUT FILE PATH
            p_path LIKE rlgrap-filename OBLIGATORY .   "Output file path
 Providing F4 help for File path : 
AT SELECTION-SCREEN OUTPUT.
 
AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
**Providing F4 help for user to enter file name
  CALL FUNCTION '/SAPDMC/LSM_F4_SERVER_FILE'
    EXPORTING
      directory        = p_file
    IMPORTING
      serverfile       = p_file
    EXCEPTIONS
      canceled_by_user = 1
      OTHERS           = 2.
  IF sy-subrc <> 0.
    MESSAGE e009(zz) WITH p_file.
  ENDIF.
 
AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_path.
**Providing F4 help for user to enter file name
  CALL FUNCTION '/SAPDMC/LSM_F4_SERVER_FILE'
    EXPORTING
      directory        = p_path
    IMPORTING
      serverfile       = p_path
    EXCEPTIONS
      canceled_by_user = 1
      OTHERS           = 2.
  IF sy-subrc <> 0.
    MESSAGE e009(zz) WITH p_path.
  ENDIF.
 To read a file from Application server : 
DATA : lv_str(50) TYPE c.
 
*Read the data from application server
OPEN DATASET p_file FOR INPUT IN TEXT  MODE ENCODING DEFAULT.
IF sy-subrc NE 0.
  MESSAGE e009(zz) WITH p_file.
 
ENDIF.
DO.
**Writing the data into internal table
  READ DATASET p_file INTO lv_str.
  IF sy-subrc = 0.
    SPLIT lv_str AT '#' INTO   gwa_file-f1
                               gwa_file-f2
                               gwa_file-f3
                               gwa_file-f4
                               gwa_file-f5
    append gwa_file to it_file.
  ELSE.
    EXIT.
  ENDIF.
ENDDO.
CLOSE DATASET p_file.
 To Upload file back to application server : 
DATA : lv_filename TYPE rlgrap-filename,
      lv_file(60) TYPE c,
        lv_string(100) TYPE c ,
        c_con_tab TYPE c VALUE cl_abap_char_utilities=>horizontal_tab.
 
CONCATENATE p_path c_filename INTO lv_filename.
**Placing the file in Application server
OPEN DATASET lv_filename FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
**Displaying error message when file is unable to open
IF sy-subrc <> 0.
  MESSAGE e009(zz) WITH lv_filename.
 
ENDIF.
LOOP AT it_final INTO gwa_final.
 
  CONCATENATE gwa_file-f1
                               gwa_file-f2
                               gwa_file-f3
                               gwa_file-f4
                               gwa_file-f5
              INTO lv_string SEPARATED BY c_con_tab.
 
  TRANSFER lv_string   TO lv_filename.
ENDLOOP.
CLOSE DATASET lv_filename.