List of all pages
Pages at first level
List of all pages
Pages at first level
List of all pages
Pages of first level
REPORT zvenkattest. PARAMETERS: p_file TYPE rlgrap-filename . START-OF-SELECTION . CALL FUNCTION 'GUI_DELETE_FILE' EXPORTING file_name = p_file EXCEPTIONS failed = 1 OTHERS = 2. IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. WRITE:/ 'the file' , p_file , 'removed successfully '.
Author: Janagar Sundaramoorthy
Submitted: <19 Feb 2009>
Description:
TMP_GUI_DIRECTORY_LIST_FILES
The function module retrieves all of the files and subdirectories on the Presentation Server (PC) for a given directory. When a value other than * or *.* is used for the filter, you will not get any directories, unless they match your wildcard filter. For example, if you entered *.png, then only files and directories that end in png will be returned by the function.
DATA: lc_directory LIKE bdschko16-target_dir VALUE 'C:\TEMP\', lc_filter(20) TYPE c VALUE '*.*', li_file_count TYPE i, li_dir_count TYPE i, ltab_dir_table LIKE sdokpath OCCURS 0 WITH HEADER LINE, ltab_file_table LIKE sdokpath OCCURS 0 WITH HEADER LINE. CALL FUNCTION 'TMP_GUI_DIRECTORY_LIST_FILES' EXPORTING directory = lc_directory filter = lc_filter IMPORTING file_count = li_file_count dir_count = li_dir_count TABLES file_table = ltab_file_table dir_table = ltab_dir_table EXCEPTIONS cntl_error = 1 OTHERS = 2.
Author: Alessandro Spadoni
Submitted: 21,Mar 2011
How to make a Zip file on Presentation Server : upload a PDF file , create a new zip file and adding to it
DATA: zip_tool TYPE REF TO cl_abap_zip, filename TYPE string VALUE 'C:\test\binfile.pdf', filename_zip TYPE string VALUE 'C:\test\zipfile.zip'. DATA: t_data_tab TYPE TABLE OF x255, bin_size TYPE i, buffer_x TYPE xstring, buffer_zip TYPE xstring. START-OF-SELECTION. **upload file from presentation server CLEAR: t_data_tab[],bin_size. CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = filename filetype = 'BIN' IMPORTING filelength = bin_size * HEADER = TABLES data_tab = t_data_tab EXCEPTIONS file_open_error = 1 file_read_error = 2 no_batch = 3 gui_refuse_filetransfer = 4 invalid_type = 5 no_authority = 6 unknown_error = 7 bad_data_format = 8 header_not_allowed = 9 separator_not_allowed = 10 header_too_long = 11 unknown_dp_error = 12 access_denied = 13 dp_out_of_memory = 14 disk_full = 15 dp_timeout = 16 OTHERS = 17 . IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. **get xstring CALL FUNCTION 'SCMS_BINARY_TO_XSTRING' EXPORTING input_length = bin_size IMPORTING buffer = buffer_x TABLES binary_tab = t_data_tab EXCEPTIONS failed = 1 OTHERS = 2. IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. **create zip tool CREATE OBJECT zip_tool. **add binary file CALL METHOD zip_tool->add EXPORTING name = 'binfile.pdf' content = buffer_x. **get binary ZIP file CALL METHOD zip_tool->save RECEIVING zip = buffer_zip. CLEAR: t_data_tab[],bin_size. CALL FUNCTION 'SCMS_XSTRING_TO_BINARY' EXPORTING buffer = buffer_zip IMPORTING output_length = bin_size TABLES binary_tab = t_data_tab. **download ZIP file CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING bin_filesize = bin_size filename = filename_zip filetype = 'BIN' TABLES data_tab = t_data_tab EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF.
"Definition of data for get download path DATA : fullpath TYPE string, filename TYPE string, path TYPE string, user_action TYPE i, encoding TYPE abap_encoding. IF p_file IS INITIAL. CALL METHOD cl_gui_frontend_services=>file_save_dialog EXPORTING window_title = 'Gui_Download Demo' with_encoding = 'X' initial_directory = 'D:\SAP' CHANGING filename = filename path = path fullpath = fullpath user_action = user_action file_encoding = encoding EXCEPTIONS cntl_error = 1 error_no_gui = 2 not_supported_by_gui = 3 OTHERS = 4. IF sy-subrc <> 0. EXIT. ENDIF. IF user_action <> cl_gui_frontend_services=>action_ok. EXIT. ENDIF. ELSE. fullpath = p_file. ENDIF. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = fullpath filetype = 'DAT' TABLES data_tab = it_top " download internal table EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
REPORT zvenkattest. DATA: file_exists TYPE xflag . PARAMETERS: file LIKE rlgrap-filename . AT SELECTION-SCREEN ON VALUE-REQUEST FOR file . CALL FUNCTION 'F4_FILENAME' EXPORTING program_name = syst-cprog dynpro_number = syst-dynnr field_name = 'FILE' IMPORTING file_name = file. START-OF-SELECTION . CALL FUNCTION 'DX_FILE_EXISTENCE_CHECK' EXPORTING filename = file pc = 'X' IMPORTING file_exists = file_exists EXCEPTIONS rfc_error = 1 frontend_error = 2 no_authority = 3 OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. IF file_exists = 'X'. WRITE:/ 'FILE EXISTS' . ELSE . WRITE:/ 'FILE doesnt EXISTS' . ENDIF.
REPORT zvenkattest. *------------------------------------------------------------* * selection screen parameters *------------------------------------------------------------* PARAMETERS: p_source LIKE rlgrap-filename , " This is the source file name p_target LIKE rlgrap-filename . " This is the target file name *------------------------------------------------------------* * start of selection *------------------------------------------------------------* START-OF-SELECTION . CALL FUNCTION 'SCMS_FILE_COPY' EXPORTING src_filename = p_source src_frontend = 'X' dst_filename = p_target dst_frontend = 'X'. *----display the output IF sy-subrc EQ 0. WRITE:/ ' the source file name was:', p_source . WRITE:/ ' the copied file name was:' , p_target . ENDIF.
REPORT zfile_with_delchar. TABLES: mara. TYPES: BEGIN OF ty_out, line(150), END OF ty_out, BEGIN OF ty_mat, matnr TYPE mara-matnr, mtart TYPE mara-mtart, mbrsh TYPE mara-mbrsh, meins TYPE mara-meins, END OF ty_mat. DATA: it_out TYPE STANDARD TABLE OF ty_out WITH HEADER LINE, it_mat TYPE STANDARD TABLE OF ty_mat WITH HEADER LINE. **--Selection-screen Design SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE title. SELECTION-SCREEN BEGIN OF LINE. SELECTION-SCREEN COMMENT 5(18) title1. SELECT-OPTIONS: s_matnr FOR mara-matnr. SELECTION-SCREEN POSITION 1 . SELECTION-SCREEN END OF LINE . SELECTION-SCREEN BEGIN OF LINE. SELECTION-SCREEN COMMENT 7(18) title2. PARAMETERS: p_dlim TYPE c OBLIGATORY. SELECTION-SCREEN POSITION 1 . SELECTION-SCREEN END OF LINE . SELECTION-SCREEN BEGIN OF LINE. SELECTION-SCREEN COMMENT 7(18) title3. PARAMETERS: p_file TYPE rlgrap-filename. SELECTION-SCREEN POSITION 1 . SELECTION-SCREEN END OF LINE . SELECTION-SCREEN END OF BLOCK b1. INITIALIZATION . title = 'enter the entries'. title1 = 'material number'. title2 = 'delimiter'. title3 = 'file name'. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file . CALL FUNCTION 'F4_FILENAME' EXPORTING program_name = syst-cprog dynpro_number = syst-dynnr field_name = 'P_FILE' IMPORTING file_name = p_file. START-OF-SELECTION. **--Get the data from material table SELECT matnr mtart mbrsh meins FROM mara INTO TABLE it_mat WHERE matnr IN s_matnr. **--Prepare output file with specified delimit char LOOP AT it_mat. IF p_dlim = 'X'. CONCATENATE it_mat-matnr it_mat-mtart it_mat-mbrsh it_mat-meins INTO it_out-line SEPARATED BY cl_abap_char_utilities=>horizontal_tab. ELSE. CONCATENATE it_mat-matnr it_mat-mtart it_mat-mbrsh it_mat-meins INTO it_out-line SEPARATED BY p_dlim. ENDIF. APPEND it_out. CLEAR: it_out, it_mat. ENDLOOP. **--Download the data DATA: file TYPE string . file = p_file . CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = file TABLES data_tab = it_out EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc = 0. WRITE:/ 'File downloaded successfully'. ENDIF.
REPORT zsave_file_pres_oops . DATA: your_file_name TYPE string, your_file_path TYPE string, the_full_path TYPE string. TYPES: BEGIN OF the_alv_structure, field1(10) TYPE c, field2(10) TYPE c, END OF the_alv_structure. DATA: the_alv_itab TYPE TABLE OF the_alv_structure. DATA: wa LIKE LINE OF the_alv_itab. wa-field1 = 'A1'. wa-field2 = 'B1'. APPEND wa TO the_alv_itab. wa-field1 = 'A2'. wa-field2 = 'B2'. APPEND wa TO the_alv_itab. wa-field1 = 'A3'. wa-field2 = 'B3'. APPEND wa TO the_alv_itab. CALL METHOD cl_gui_frontend_services=>file_save_dialog EXPORTING default_extension = '.xls' default_file_name = 'Text' CHANGING filename = your_file_name path = your_file_path fullpath = the_full_path. CALL METHOD cl_gui_frontend_services=>gui_download EXPORTING filename = the_full_path write_field_separator = 'X' CHANGING data_tab = the_alv_itab.
With this FM we can open our file that we have in byte form (for example: passed by a WebServices) in default presentation server application.
File will be saved in a system temp directory and then open.
To do this we have to pass to the function:
- file name with extension (so the system will know which application should be used to open it)
- file data in byte tab (for example: it can be SOLIX structure or table of X buffer)
FUNCTION ZFILE_OPEN. *"---------------------------------------------------------------------- *"*"Lokalny interfejs: *" IMPORTING *" REFERENCE(FILE_NAME) TYPE STRING *" TABLES *" XTAB *"---------------------------------------------------------------------- DATA: temp_dir TYPE string, separator TYPE c, lfname TYPE string, codepage LIKE tcp00-cpcodepage, dyn_codepage LIKE tcp00-cpcodepage, aba_codepage TYPE abap_encod. * Get the Path to the TEMP Directory CALL METHOD cl_gui_frontend_services=>get_temp_directory CHANGING temp_dir = temp_dir. CALL METHOD cl_gui_cfw=>flush EXCEPTIONS cntl_system_error = 1 cntl_error = 2 OTHERS = 3. IF sy-subrc <> 0. ENDIF. * Get the system`s separator CALL METHOD cl_gui_frontend_services=>get_file_separator CHANGING file_separator = separator. CALL METHOD cl_gui_cfw=>flush EXCEPTIONS cntl_system_error = 1 cntl_error = 2 OTHERS = 3. IF sy-subrc <> 0. ENDIF. * Concatenate file path CONCATENATE temp_dir separator file_name INTO lfname. * Get system codepage CALL FUNCTION 'SYSTEM_CODEPAGE' IMPORTING codepage = codepage current_dynamic_codepage = dyn_codepage. aba_codepage = dyn_codepage. * Save XTAB to file CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = lfname codepage = aba_codepage TABLES data_tab = xtab. IF sy-subrc <> 0. ENDIF. * Execute default file aplication CALL METHOD cl_gui_frontend_services=>execute EXPORTING document = lfname EXCEPTIONS cntl_error = 1 error_no_gui = 2 bad_parameter = 3 file_not_found = 4 path_not_found = 5 file_extension_unknown = 6 error_execute_failed = 7 OTHERS = 8. IF sy-subrc <> 0. ENDIF. ENDFUNCTION.
REPORT zvenkattest. *---------------------------------------------------------------------------------------* * selection screen design *---------------------------------------------------------------------------------------* PARAMETERS: p_file LIKE rlgrap-filename . *---------------------------------------------------------------------------------------* * data declarations *---------------------------------------------------------------------------------------* DATA: pathname TYPE char50 , filename TYPE char50 . *---------------------------------------------------------------------------------------* * at selection screen for field *---------------------------------------------------------------------------------------* AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file . CALL FUNCTION 'F4_FILENAME' EXPORTING program_name = syst-cprog dynpro_number = syst-dynnr field_name = 'P_FILE' IMPORTING file_name = p_file. *---------------------------------------------------------------------------------------* * start of selection *---------------------------------------------------------------------------------------* START-OF-SELECTION . CALL FUNCTION '/SAPDMC/LSM_PATH_FILE_SPLIT' EXPORTING pathfile = p_file IMPORTING pathname = pathname filename = filename. *---------------------------------------------------------------------------------------* * display output *---------------------------------------------------------------------------------------* WRITE:/ 'PATHNAME IS : ' ,pathname . WRITE:/ 'FILENAME IS : ' ,filename .
List of all pages
Pages at first level
REPORT zdownload_file. DATA: BEGIN OF itab OCCURS 0, field1 TYPE char9, field2 TYPE char2, field3 TYPE char2, END OF itab. DATA: output(100) TYPE c. PARAMETERS: p_file TYPE localfile . START-OF-SELECTION. itab-field1 = 'name1'. itab-field2 = '11'. itab-field3 = '23' . APPEND itab . itab-field1 = 'name2'. itab-field2 = '41'. itab-field3 = '53' . APPEND itab . itab-field1 = 'name3'. itab-field2 = '53'. itab-field3 = '87' . APPEND itab . OPEN DATASET p_file FOR OUTPUT IN TEXT MODE ENCODING DEFAULT . LOOP AT itab. CONCATENATE itab-field1 itab-field2 itab-field3 INTO output SEPARATED BY ','. TRANSFER output TO p_file. ENDLOOP. CLOSE DATASET p_file.
Program for writing into application server from Internal table
REPORT z_opendataset_output. *--------------------------------------------------------------------------------------* * variable declaration *--------------------------------------------------------------------------------------* DATA: w_file(80) TYPE c , w_count TYPE i VALUE 0, w_log(310) TYPE c. *-----------------------------------------------------------------------------------* * internal table declarations *----------------------------------------------------------------------------------* DATA: BEGIN OF it_log OCCURS 0, w_vbeln LIKE vbap-vbeln, "Sales Document w_posnr(6) , " Sales Document Item w_matnr(18) , " material no w_cname(30) , " characteristic name w_ovalue(90) , " old value of characteristic w_nvalue(90) , " new value of characteristic END OF it_log . *-----work area for the table DATA: wa_it_log LIKE LINE OF it_log. *---------------------------------------------------------------------------------------* * selection screen *--------------------------------------------------------------------------------------* PARAMETERS: p_file TYPE ibipparms-path. *---------------------------------------------------------------------------------------* * start of selection *--------------------------------------------------------------------------------------* START-OF-SELECTION . *----this is for the file upload PERFORM log_file_upload. *---------------------------------------------------------------------------------------* * file upload *--------------------------------------------------------------------------------------* FORM log_file_upload . DATA: l_msg(80) TYPE c, l_name(200) TYPE c, l_ext(5) TYPE c, l_file(300) TYPE c. MOVE p_file TO w_file. *----get the count of lines in the table DESCRIBE TABLE it_log LINES w_count. IF NOT w_count IS INITIAL. OPEN DATASET w_log FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. IF sy-subrc <> 0. WRITE:/ 'Error in opening file'. ELSE. *----Setting header wa_it_log-w_vbeln = 'Order'. wa_it_log-w_posnr = 'Item'. wa_it_log-w_matnr = 'Material'. wa_it_log-w_cname = 'Char Name'. wa_it_log-w_ovalue = 'Old Value'. wa_it_log-w_nvalue = 'New Value'. TRANSFER wa_it_log TO w_log. MOVE: sy-uline(255) TO wa_it_log. TRANSFER wa_it_log TO w_log. MOVE: ' ' TO wa_it_log. TRANSFER wa_it_log TO w_log. LOOP AT it_log. CLEAR wa_it_log. wa_it_log-w_vbeln = it_log-w_vbeln. wa_it_log-w_posnr = it_log-w_posnr. wa_it_log-w_matnr = it_log-w_matnr. wa_it_log-w_cname = it_log-w_cname. wa_it_log-w_ovalue = it_log-w_ovalue. wa_it_log-w_nvalue = it_log-w_nvalue. TRANSFER wa_it_log TO w_log. CLEAR w_excel_string. ENDLOOP. *---text-307 'log file saved successfully to :' CONCATENATE text-307 w_log INTO l_msg SEPARATED BY space. MESSAGE l_msg TYPE 'S'. ENDIF. ENDIF. ENDFORM. " log_file_upload
Declare input and output file parameters on selection screen
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. * Writing the file to the Application server OPEN DATASET lv_filename FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. 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.
*To Open the file from application server : OPEN DATASET p_file FOR INPUT IN TEXT MODE ENCODING DEFAULT. IF sy-subrc NE 0. MESSAGE e009(message CLASS ) WITH p_file. " Displaying an error message when file is not opened ENDIF. DO. * to read the data from file to a string READ DATASET p_file INTO lv_str. IF sy-subrc = 0. SPLIT lv_str AT '#' INTO gwa_file-country_code. gwa_file-f1 gwa_file-f2 gwa_file-f3 gwa_file-f4 . APPEND gwa_file TO it_file. ELSE. EXIT. ENDIF. ENDDO. CLOSE DATASET p_file.
Applies to:
This document applies to SAP ECC 6.0, SAP Netweaver 2004s. For more information, visit the ABAP homepage.
Summary
This program is used to perform file operation such as Delete\ upload\ download from application server. There is no standard transaction to delete file from application server. So this sample code can be useful when someone wants to delete a file from application server.
Author: Sourabh Batwara
Company: Cognizant Technology Solution
Submitted: 1st December 2010
Author Bio:
Sourabh Batwara is working in Cognizant technology solution as a SAP Consultant. He has 4.5 years of experience in SAP.
Description
While working with file interface we have to delete, upload or download files from application server. but for deletion, there is no standard transaction available in SAP. This program will help to delete file from application server.
Selection screen shots
Upload File:
Download File
Delete File
Program Code
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'*----------------------------------------------------------------------- * Program Name : ZSB_FILE_OPERATION * Creation date : 01.12.2010 * Description : This Test program is used to perform file * operation on application server such as delete/upload/download. *----------------------------------------------------------------------- REPORT zsb_file_operation. *----------------------------------------------------------------------* * DATA DECLEARATION * *----------------------------------------------------------------------* * boolean constants for function-parameters and other objects TYPE-POOLS: esp1. * Boolean values TYPES: boolean TYPE esp1_boolean. DATA: p_file(128), " File path lv_ans, " Popup answer lv_flag LIKE bapistdtyp-boolean. CONSTANTS : c_yes TYPE c VALUE '1', c_no TYPE c VALUE '0', c_upload(4) TYPE c VALUE 'CG3Z', c_dnload(4) TYPE c VALUE 'CG3Y', c_x TYPE c VALUE 'X', c_j TYPE c VALUE 'J', c_n TYPE c VALUE 'N', true TYPE boolean VALUE esp1_true. *----------------------------------------------------------------------* * SELECTION SCREEN * *----------------------------------------------------------------------* SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001. PARAMETERS : r_upload RADIOBUTTON GROUP rb1 USER-COMMAND del DEFAULT 'X', " Upload file r_dnload RADIOBUTTON GROUP rb1, " Download file r_delete RADIOBUTTON GROUP rb1. " Delete file SELECTION-SCREEN END OF BLOCK b1. SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-002. PARAMETERS: p_dir LIKE rlgrap-filename MODIF ID del, " Dir Path p_file1 LIKE rlgrap-filename MODIF ID del. " Path name SELECTION-SCREEN END OF BLOCK b2. SELECTION-SCREEN BEGIN OF BLOCK b3 WITH FRAME TITLE text-003. PARAMETERS: p_local LIKE rcgfiletr-ftfront MODIF ID up, " Dir Path p_path LIKE rcgfiletr-ftappl MODIF ID up, " Path name p_over AS CHECKBOX MODIF ID up. " Overwrite SELECTION-SCREEN END OF BLOCK b3. SELECTION-SCREEN BEGIN OF BLOCK b4 WITH FRAME TITLE text-004. PARAMETERS: p_path1 LIKE rcgfiletr-ftappl MODIF ID dn, " Path name p_local1 LIKE rcgfiletr-ftfront MODIF ID dn, " Dir Path p_over1 AS CHECKBOX MODIF ID dn. SELECTION-SCREEN END OF BLOCK b4. *----------------------------------------------------------------------* * AT SELECTION SCREEN OUTPUT * *----------------------------------------------------------------------* AT SELECTION-SCREEN OUTPUT. LOOP AT SCREEN. IF screen-group1 = 'DEL'. IF r_delete = c_x. screen-invisible = c_no . screen-active = c_yes . ELSE. screen-invisible = c_yes . screen-active = c_no . ENDIF. MODIFY SCREEN. ENDIF. IF screen-group1 = 'UP'. IF r_upload = c_x. screen-invisible = c_no . screen-active = c_yes . ELSE. screen-invisible = c_yes . screen-active = c_no . ENDIF. MODIFY SCREEN. ENDIF. IF screen-group1 = 'DN'. IF r_dnload = c_x. screen-invisible = c_no . screen-active = c_yes . ELSE. screen-invisible = c_yes . screen-active = c_no . ENDIF. MODIFY SCREEN. ENDIF. ENDLOOP. *----------------------------------------------------------------------* * AT SELECTION SCREEN ON VALUE REQUEST * *----------------------------------------------------------------------* AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_local. CALL FUNCTION 'F4_FILENAME' EXPORTING field_name = 'P_LOCAL' IMPORTING file_name = p_local. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_local1. CALL FUNCTION 'F4_FILENAME' EXPORTING field_name = 'P_LOCAL1' IMPORTING file_name = p_local1. *----------------------------------------------------------------------* * START OF SELECTION * *----------------------------------------------------------------------* START-OF-SELECTION. IF r_upload = c_x. PERFORM file_upload. ELSEIF r_dnload = c_x. PERFORM file_dnload. ELSE. PERFORM file_delete. ENDIF. *&---------------------------------------------------------------------* *& Form FILE_UPLOAD *&---------------------------------------------------------------------* * Form to upload file from frontend to application server *----------------------------------------------------------------------* FORM file_upload . CLEAR lv_flag. IF p_over = c_x. lv_flag = 1. ENDIF. CALL FUNCTION 'C13Z_FILE_UPLOAD_BINARY' EXPORTING i_file_front_end = p_local i_file_appl = p_path i_file_overwrite = lv_flag EXCEPTIONS fe_file_not_exists = 1 fe_file_read_error = 2 ap_no_authority = 3 ap_file_open_error = 4 ap_file_exists = 5. CASE sy-subrc. WHEN '0'. MESSAGE s899(bd) WITH 'File uploaded successfully'. WHEN '1'. MESSAGE e899(bd) WITH 'File does not exist'. WHEN '2'. MESSAGE e899(bd) WITH 'Error in file reading'. WHEN '3'. MESSAGE e899(bd) WITH 'Authorization Error'. WHEN '5'. * file already exists, ask if file can be overwritten CALL FUNCTION 'C14A_POPUP_ASK_FILE_OVERWRITE' IMPORTING e_flg_continue = lv_flag EXCEPTIONS OTHERS = 1. IF sy-subrc = 0 AND lv_flag = true. CALL FUNCTION 'C13Z_FILE_UPLOAD_BINARY' EXPORTING i_file_front_end = p_local i_file_appl = p_path i_file_overwrite = lv_flag. IF sy-subrc IS INITIAL. MESSAGE s899(bd) WITH 'File uploaded successfully'. ENDIF. ENDIF. ENDCASE. ENDFORM. " FILE_UPLOAD *&---------------------------------------------------------------------* *& Form FILE_DNLOAD *&---------------------------------------------------------------------* * Form to download the file from application server to frontend *----------------------------------------------------------------------* FORM file_dnload . CLEAR lv_flag. IF p_over1 = c_x. lv_flag = 1. ENDIF. CALL FUNCTION 'C13Z_FILE_DOWNLOAD_BINARY' EXPORTING i_file_front_end = p_local1 i_file_appl = p_path1 i_file_overwrite = lv_flag EXCEPTIONS fe_file_open_error = 1 fe_file_exists = 2 ap_no_authority = 4. CASE sy-subrc. WHEN '0'. MESSAGE s899(bd) WITH 'File downloaded successfully'. WHEN '1'. MESSAGE e899(bd) WITH 'Error while opening file'. WHEN '2'. * file already exists, ask if file can be overwritten CALL FUNCTION 'C14A_POPUP_ASK_FILE_OVERWRITE' IMPORTING e_flg_continue = lv_flag EXCEPTIONS OTHERS = 1. IF sy-subrc = 0 AND lv_flag = true. CALL FUNCTION 'C13Z_FILE_DOWNLOAD_BINARY' EXPORTING i_file_front_end = p_local1 i_file_appl = p_path1 i_file_overwrite = lv_flag. IF sy-subrc IS INITIAL. MESSAGE s899(bd) WITH 'File downloaded successfully'. ENDIF. ENDIF. WHEN '4'. MESSAGE e899(bd) WITH 'Authorization Error'. ENDCASE. ENDFORM. " FILE_DNLOAD *----------------------------------------------------------------------* * Form FILE_DELETE * *----------------------------------------------------------------------* * Form to delete file from application server * *----------------------------------------------------------------------* FORM file_delete . * File path CONCATENATE p_dir p_file1 INTO p_file. * Check file exists OPEN DATASET p_file FOR INPUT IN BINARY MODE. IF sy-subrc NE 0. MESSAGE e899(bd) WITH p_file 'does not exist'. EXIT. ELSE. * Popup window CALL FUNCTION 'POPUP_CONTINUE_YES_NO' EXPORTING defaultoption = c_n textline1 = p_file titel = 'Are you sure to delete this file?' IMPORTING answer = lv_ans EXCEPTIONS OTHERS = 1. ENDIF. CLOSE DATASET p_file. IF lv_ans EQ c_j. * Delete file DELETE DATASET p_file. IF sy-subrc NE 0. MESSAGE e899(bd) WITH 'Invalid file name' p_file. ELSE. CLOSE DATASET p_file. MESSAGE s899(bd) WITH p_dir p_file1 'has been deleted'. ENDIF. ENDIF. ENDFORM. " FILE_DELETE
REPORT zdelete. *----------------------------------------------------------------------* * Delete a file on the application server. *----------------------------------------------------------------------* PARAMETERS: p_dir LIKE rlgrap-filename DEFAULT '/usr/sap/trans/', p_file1 LIKE rlgrap-filename. DATA: p_file(128). DATA: w_ans. START-OF-SELECTION. CONCATENATE p_dir p_file1 INTO p_file. *----------------------------------------------------------------------* * check file exists *----------------------------------------------------------------------* OPEN DATASET p_file FOR INPUT IN TEXT MODE ENCODING DEFAULT. IF sy-subrc NE 0. MESSAGE e899(bd) WITH p_file 'DOES NOT EXIST'. EXIT. ELSE. CALL FUNCTION 'POPUP_CONTINUE_YES_NO' EXPORTING defaultoption = 'N' textline1 = p_dir textline2 = p_file1 titel = 'ARE YOU SURE YOU WANT TO DELETE' IMPORTING answer = w_ans EXCEPTIONS OTHERS = 1. ENDIF. CLOSE DATASET p_file. CHECK w_ans = 'J'. *----------------------------------------------------------------------* * delete *----------------------------------------------------------------------* DELETE DATASET p_file. IF sy-subrc NE 0. MESSAGE e899(bd) WITH 'INVALID FILE NAME' p_file. ELSE. CLOSE DATASET p_file. MESSAGE i899(bd) WITH p_dir p_file1 'DELETED SUCCESFULLY'. ENDIF.
Output:-
*Enter the Directory name & File Name *
*Press F8*
*Press Enter*
*Go to Transcation AL11 ->Double Click on DIR_TEMP-> You can find the List of file*
*Before Deleting the File*
*After Deleting the File*
When you access sequential files on the application server using the following statements
- OPEN DATASET
- READ DATASET
- TRANSFER
- DELETE DATASET
the system automatically checks the user’s authorization against the authorization object S_DATASET. Based on the User Role and Authorizations the above activities will be possible.
Hence the developers must check the authorization in ABAP program before accessing the file using the function module AUTHORITY_CHECK_DATASET.
REPORT zshiva_itab_to_xml_app_server. TYPE-POOLS: ixml. TYPES: BEGIN OF xml_line, data(256) TYPE x, END OF xml_line. DATA fname(30) VALUE 'D:\XML\shiva.XML'. DATA: l_ixml TYPE REF TO if_ixml, l_streamfactory TYPE REF TO if_ixml_stream_factory, l_ostream TYPE REF TO if_ixml_ostream, l_renderer TYPE REF TO if_ixml_renderer, l_document TYPE REF TO if_ixml_document. DATA: l_element_flights TYPE REF TO if_ixml_element, l_element_airline TYPE REF TO if_ixml_element, l_element_flight TYPE REF TO if_ixml_element, l_element_from TYPE REF TO if_ixml_element, l_element_to TYPE REF TO if_ixml_element, l_element_dummy TYPE REF TO if_ixml_element, l_value TYPE string. DATA: l_xml_table TYPE TABLE OF xml_line, rec TYPE xml_line, l_xml_size TYPE i, l_rc TYPE i. DATA: lt_spfli TYPE TABLE OF spfli. DATA: l_spfli TYPE spfli. START-OF-SELECTION. * Fill the internal table SELECT * FROM spfli INTO TABLE lt_spfli. * Sort internal table SORT lt_spfli BY carrid. * Start filling xml dom object from internal table LOOP AT lt_spfli INTO l_spfli. AT FIRST. * Creating a ixml factory l_ixml = cl_ixml=>create( ). * Creating the dom object model l_document = l_ixml->create_document( ). * Fill root node with value flights l_element_flights = l_document->create_simple_element( name = 'flights' parent = l_document ). ENDAT. AT NEW carrid. * Create element 'airline' as child of 'flights' l_element_airline = l_document->create_simple_element( name = 'airline' parent = l_element_flights ). * Create attribute 'code' of node 'airline' l_value = l_spfli-carrid. l_rc = l_element_airline->set_attribute( name = 'code' value = l_value ). * Create attribute 'name' of node 'airline' SELECT SINGLE carrname FROM scarr INTO l_value WHERE carrid EQ l_spfli-carrid. l_rc = l_element_airline->set_attribute( name = 'name' value = l_value ). ENDAT. AT NEW connid. * Create element 'flight' as child of 'airline' l_element_flight = l_document->create_simple_element( name = 'flight' parent = l_element_airline ). * Create attribute 'number' of node 'flight' l_value = l_spfli-connid. l_rc = l_element_flight->set_attribute( name = 'number' value = l_value ). ENDAT. * Create element 'from' as child of 'flight' CONCATENATE l_spfli-cityfrom ',' l_spfli-countryfr INTO l_value. l_element_from = l_document->create_simple_element( name = 'from' value = l_value parent = l_element_flight ). * Create attribute 'airport' of node 'from' l_value = l_spfli-airpfrom. l_rc = l_element_from->set_attribute( name = 'airport' value = l_value ). * Create element 'to' as child of 'flight' CONCATENATE l_spfli-cityto ',' l_spfli-countryto INTO l_value. l_element_to = l_document->create_simple_element( name = 'to' value = l_value parent = l_element_flight ). * Create attribute 'airport' of node 'from' l_value = l_spfli-airpto. l_rc = l_element_to->set_attribute( name = 'airport' value = l_value ). * Create element 'departure' as child of 'flight' l_value = l_spfli-deptime. l_element_dummy = l_document->create_simple_element( name = 'departure' value = l_value parent = l_element_flight ). * Create element 'arrival' as child of 'flight' l_value = l_spfli-arrtime. l_element_dummy = l_document->create_simple_element( name = 'arrival' value = l_value parent = l_element_flight ). * Create element 'type' as child of 'flight' CASE l_spfli-fltype. WHEN 'X'. l_value = 'Charter'. WHEN OTHERS. l_value = 'Scheduled'. ENDCASE. l_element_dummy = l_document->create_simple_element( name = 'type' value = l_value parent = l_element_flight ). ENDLOOP. IF sy-subrc NE 0. MESSAGE 'No data into db table ''spfli'', please run program ''SAPBC_DATA_GENERATOR'' with transaction ''SA38''' TYPE 'E'. ENDIF. * Creating a stream factory l_streamfactory = l_ixml->create_stream_factory( ). * Connect internal XML table to stream factory l_ostream = l_streamfactory->create_ostream_itable( table = l_xml_table ). * Rendering the document l_renderer = l_ixml->create_renderer( ostream = l_ostream document = l_document ). l_rc = l_renderer->render( ). * Saving the XML document l_xml_size = l_ostream->get_num_written_raw( ). * OPEN DATASET fname FOR OUTPUT IN BINARY MODE. IF sy-subrc EQ 0. LOOP AT l_xml_table INTO rec. TRANSFER rec TO fname. ENDLOOP. CLOSE DATASET fname. ENDIF.
Author: Vivek Priyadarshi
Submitted: 06/17/2015
Related Links:
- <link>
Description I recently worked on a requirement where a functionality was required to get the modification date of a file on application server and make some decisions based on the same. In this blog, I will discussed a simple technique to get this information for any file stored on the application server. This code resembles the logic in function module EPS_GET_FILE_ATTRIBUTES with minor adjustments (mostly for the modification date property).
/* your snippet */ *----------------------------------------------------------------------* * CLASS lcl_file_property DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_file_property DEFINITION FINAL CREATE PUBLIC. PUBLIC SECTION. TYPES: BEGIN OF ty_file_property , dirname(75) TYPE c, " name of directory. (possibly truncated.) name(75) TYPE c, " name of entry. (possibly truncated.) type(10) TYPE c, " type of entry. len(8) TYPE p DECIMALS 0, " length in bytes. owner(8) TYPE c, " owner of the entry. mtime(10) TYPE p DECIMALS 0, " last modification date, seconds since 1970 mdate TYPE datum, mode(9) TYPE c, " like "rwx-r-x--x": protection mode. errno(3) TYPE c, errmsg(40) TYPE c, END OF ty_file_property. DATA: directory_name TYPE line, file_property TYPE ty_file_property, file_property_t TYPE STANDARD TABLE OF ty_file_property. DATA: lv_mgr_user TYPE as4user, lv_eps_subdir TYPE epsf-epssubdir. DATA: lt_dir_list TYPE STANDARD TABLE OF epsfili, dir_list LIKE LINE OF lt_dir_list, file_counter TYPE epsf-epsfilsiz, error_counter TYPE epsf-epsfilsiz, lv_unix_path TYPE char255. DATA: lt_sections TYPE stringtab, lv_section TYPE string, lv_filename TYPE epsf-epsfilnam, lv_rows TYPE i. METHODS: constructor IMPORTING directory_path TYPE char255, get_file_properties RETURNING value(properties) TYPE ty_file_property. PRIVATE SECTION. CONSTANTS: gc_secs_in_day TYPE i VALUE 86400. METHODS: calculate_modification_date IMPORTING property TYPE ty_file_property RETURNING value(mod_date) TYPE datum. ENDCLASS. "lcl_file_property DEFINITION *----------------------------------------------------------------------* * CLASS lcl_file_property IMPLEMENTATION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS lcl_file_property IMPLEMENTATION. METHOD constructor. directory_name = directory_path. *--- Split path to get the file name SPLIT directory_name AT '/' INTO TABLE lt_sections. lv_rows = lines( lt_sections ). READ TABLE lt_sections INTO lv_section INDEX lv_rows. CHECK sy-subrc EQ 0. lv_filename = lv_section. *----- Remove filename from directory path REPLACE FIRST OCCURRENCE OF lv_section IN directory_name WITH space. CONDENSE directory_name. ENDMETHOD. "constructor METHOD get_file_properties. * get directory listing CALL 'C_DIR_READ_FINISH' " just to be sure ID 'ERRNO' FIELD file_property-errno ID 'ERRMSG' FIELD file_property-errmsg. CALL 'C_DIR_READ_START' ID 'DIR' FIELD directory_name ID 'FILE' FIELD lv_filename ID 'ERRNO' FIELD file_property-errno ID 'ERRMSG' FIELD file_property-errmsg. IF sy-subrc <> 0. *** RAISE EXCEPTION TYPE zcx_unix_file_base *** EXPORTING *** textid = zcx_unix_file_base=>read_directory_failed *** unix_path = lv_unix_path. MESSAGE 'Error during reading content of directory path' TYPE 'E'. ENDIF. REFRESH lt_dir_list. CLEAR file_counter. CLEAR error_counter. DO. CLEAR file_property. CLEAR dir_list. CALL 'C_DIR_READ_NEXT' ID 'TYPE' FIELD file_property-type ID 'NAME' FIELD file_property-name ID 'LEN' FIELD file_property-len ID 'OWNER' FIELD file_property-owner ID 'MTIME' FIELD file_property-mtime ID 'MODE' FIELD file_property-mode ID 'ERRNO' FIELD file_property-errno ID 'ERRMSG' FIELD file_property-errmsg. * handle files > 2147483647 byte (int 4) - hen 9.9.2004 IF file_property-len > 2147483647. dir_list-size = -99. ELSE. dir_list-size = file_property-len. ENDIF. dir_list-name = file_property-name. IF sy-subrc = 0. IF file_property-type(1) = 'f' OR " regular file file_property-type(1) = 'F'. ADD 1 TO file_counter. dir_list-rc = 0. APPEND dir_list TO lt_dir_list. file_property-mdate = me->calculate_modification_date( file_property ). APPEND file_property TO file_property_t. ENDIF. ELSEIF sy-subrc = 1. EXIT. ELSE. IF error_counter > 1000. CALL 'C_DIR_READ_FINISH' ID 'ERRNO' FIELD file_property-errno ID 'ERRMSG' FIELD file_property-errmsg. *** RAISE EXCEPTION TYPE zcx_unix_file_base *** EXPORTING *** textid = zcx_unix_file_base=>too_many_read_errors. MESSAGE 'Too many read errors' TYPE 'E'. ENDIF. ADD 1 TO error_counter. dir_list-rc = 18. APPEND dir_list TO lt_dir_list. file_property-mdate = me->calculate_modification_date( file_property ). APPEND file_property TO file_property_t. ENDIF. ENDDO. CALL 'C_DIR_READ_FINISH' ID 'ERRNO' FIELD file_property-errno ID 'ERRMSG' FIELD file_property-errmsg. IF file_counter > 0. SORT lt_dir_list BY name ASCENDING. READ TABLE file_property_t INTO file_property INDEX 1. CHECK sy-subrc EQ 0. properties = file_property. ELSE. *** RAISE EXCEPTION TYPE zcx_unix_file_base *** EXPORTING *** textid = zcx_unix_file_base=>empty_directory_list. MESSAGE 'Directory list is empty' TYPE 'E'. ENDIF. properties = file_property. ENDMETHOD. "get_file_properties METHOD calculate_modification_date. DATA: lv_days TYPE p LENGTH 10 DECIMALS 4, lv_seconds TYPE p LENGTH 10 DECIMALS 0, lv_date TYPE sy-datum VALUE '19691231'. CHECK NOT property-mtime IS INITIAL. *----- 1 Day = 86400 Seconds *----- Get number of days from seconds lv_seconds = property-mtime. lv_days = lv_seconds / me->gc_secs_in_day. lv_date = lv_date + lv_days. mod_date = lv_date. ENDMETHOD. "calculate_modification_date ENDCLASS. "lcl_file_property IMPLEMENTATION
Naresh
Dec 10 2007
Description: ABAP code for retrieving list of files contained within specific Application server directory(SAP).
*&---------------------------------------------------------------------*
*& Report ZDIRFILES *
*&---------------------------------------------------------------------*
REPORT ZDIRFILES .
PARAMETER: p_fdir type pfeflnamel DEFAULT '/usr/sap/tmp'.
data: begin of it_filedir occurs 10.
include structure salfldir.
data: end of it_filedir.
************************************************************************
*START-OF-SELECTION
START-OF-SELECTION.
* Get Current Directory Listing for OUT Dir
call function 'RZL_READ_DIR_LOCAL'
exporting
name = p_fdir
tables
file_tbl = it_filedir.
* List of files are contained within table it_filedir
loop at it_filedir.
write: / it_filedir-NAME.
endloop.
To get an F4 help of the application server directories:
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'PARAMETERS : p_dir TYPE char30 LOWER CASE. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_dir. CALL FUNCTION '/SAPDMC/LSM_F4_SERVER_FILE' EXPORTING directory = p_dir IMPORTING serverfile = p_dir EXCEPTIONS canceled_by_user = 1 OTHERS = 2.
Subroutine/method to compress a binary file into an existing .zip file.
Payload
io_zip->add( name = iv_file_name content = iv_file_content ). io_zip->save( ).
Signature
FORM zip USING io_zip_file TYPE REF TO cl_abap_zip iv_file_name TYPE csequence iv_file_content TYPE xstring. ENDFORM. OR METHODS zip IMPORTING io_zip_file TYPE REF TO cl_abap_zip iv_file_name TYPE csequence iv_file_content TYPE xstring. METHOD zip. ENDMETHOD.
Below Code will read the Files in ZIP Folder Using Class cl_abap_zip.
Using CL_ABAP_ZIP we can add multiple file to ZIP Folder and we can Read added files in ZIP.
Get the File Content of type XSTRING from Upload UI Element and Pass it to Method LOAD of Class CL_ABAP_ZIP after creating instance of Class.
DATA lo_zipobj TYPE REF TO cl_abap_zip. CREATE OBJECT lo_zipobj. " Instances of class CALL METHOD lo_zipobj->load EXPORTING zip = lv_filecontent. " lv_filecontent is ZIP File Content of type XSTRING *Attribute FILES will have number of files in the ZIP. *Using Get file Method of class CL_ABAP_ZIP get the file content from ZIP and pass it to method READ as below. LOOP AT lo_zipobj->files INTO ls_files. CALL METHOD lo_zipobj->get EXPORTING name = ls_files-name IMPORTING content = lv_xstring. CALL METHOD cl_abap_conv_in_ce=>create EXPORTING input = lv_xstring encoding = 'UTF-8' replacement = '?' ignore_cerr = abap_true RECEIVING conv = l_addr. CALL METHOD l_addr->read IMPORTING data = l_string. ENDLOOP.
Each loop pass l_string will have ZIP Folder File Content
The below program is a sample code on how to transfer files from a FTP Directory into SAP Application server directory. This program will :
(1) Read the files in a particular directory - FTP
(2) Copy the files in to the SAP directory - SAP Application Server
(3) Delete the original file from FTP server.
Additionally a Log table has been created which will track the status of the file.
Table structure - ZTBL_IPL_FTP as below :
FILE_NM |
ZDA_FILNAM |
CHAR |
110 |
0 |
File Name for LPI Files |
LOG_ID |
ZDA_LOG_LPI |
NUMC |
4 |
0 |
Log Id for LPI File |
FDATE |
SYDATUM |
DATS |
8 |
0 |
Current Date of Application Server |
FTIME |
SYUZEIT |
TIMS |
6 |
0 |
Current Time of Application Server |
STAT |
ZSTAT_LPI |
CHAR |
2 |
0 |
Status of file |
MESS |
BAPI_MSG |
CHAR |
220 |
0 |
Message Text |
Code as below :
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'REPORT zftptrasfr NO STANDARD PAGE HEADING LINE-SIZE 255. ************************************************************************ *T Y P E S ************************************************************************ TYPES: BEGIN OF x_cmdout, line(100) TYPE c, END OF x_cmdout. TYPE-POOLS : slis. ************************************************************************ * D A T A ************************************************************************ *data specifications of FTP server *Handler and Key DATA: w_cmd(40) TYPE c, w_hdl TYPE i, w_logid TYPE zda_log_ipl VALUE 1, w_key TYPE i VALUE 26101957, w_slen TYPE i, wa_iplftp TYPE ztbl_ipl_ftp, it_iplftp TYPE STANDARD TABLE OF ztbl_ipl_ftp, wa_cmdout TYPE x_cmdout, it_cmdout TYPE STANDARD TABLE OF x_cmdout. *Constant declarations CONSTANTS: c_dest TYPE rfcdes-rfcdest VALUE 'SAPFTPA', c_host(11) TYPE c VALUE '172.XX.X.XX', c_ftp(6) TYPE c VALUE 'FTPDIRECTORY', c_sap(16) TYPE c VALUE '/sap/inbound/SAPDIRECTORY'. ************************************************************************ * P A R A M E T E R S ************************************************************************ SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001. PARAMETERS: p_user(30) TYPE c LOWER CASE , p_pwd(30) TYPE c LOWER CASE , p_host(64) TYPE c LOWER CASE DEFAULT c_host , p_edi TYPE zedi, " 5-character domain containing EDI profiles p_ftp TYPE e_dexcommfilepath LOWER CASE DEFAULT c_ftp, p_sap TYPE esefilepath LOWER CASE DEFAULT c_sap. SELECTION-SCREEN END OF BLOCK b1. ************************************************************************ *AT SELECTION SCREEN Events ************************************************************************ AT SELECTION-SCREEN OUTPUT. LOOP AT SCREEN. CASE screen-name. WHEN 'P_PWD'."Set the password field as invisible screen-invisible = '1'. MODIFY SCREEN. ENDCASE. ENDLOOP. ************************************************************************ * S T A R T - O F - S E L E C T I O N ************************************************************************ START-OF-SELECTION. *Connect to the FTP server. PERFORM ftp_connect. *Find all files in the directory and store inside the Log table PERFORM log_files. *Check for transfer of files to FTP. IF it_iplftp[] IS INITIAL. MESSAGE text-003 TYPE 'I'. LEAVE LIST-PROCESSING. ENDIF. *Change the local save directory and download to SAP application server. PERFORM move_files. *Close the connection PERFORM close_ftp. ************************************************************************ *END-OF-SELECTION ************************************************************************ END-OF-SELECTION. *Display report. PERFORM disp_res. *&--------------------------------------------------------------------- *& Form FTP_CONNECT *&--------------------------------------------------------------------- *Make a connection to the FTP server *---------------------------------------------------------------------- FORM ftp_connect . SET EXTENDED CHECK OFF. w_slen = strlen( p_pwd ). CALL FUNCTION 'HTTP_SCRAMBLE' EXPORTING source = p_pwd sourcelen = w_slen key = w_key IMPORTING destination = p_pwd. CALL FUNCTION 'FTP_CONNECT' EXPORTING user = p_user password = p_pwd host = p_host rfc_destination = c_dest IMPORTING handle = w_hdl EXCEPTIONS not_connected = 1 OTHERS = 2. IF sy-subrc <> 0. *Message will arise in case of any issues in connecting to the FTP server. MESSAGE text-e01 TYPE 'I'. LEAVE LIST-PROCESSING. ENDIF. ENDFORM. " FTP_CONNECT *&--------------------------------------------------------------------- *& Form LOG_FILES *&--------------------------------------------------------------------- *find all the files in the home directory *---------------------------------------------------------------------- FORM log_files . *Change directory to the FTP directory for LUPIN CONCATENATE 'cd' p_ftp INTO w_cmd SEPARATED BY space. CALL FUNCTION 'FTP_COMMAND' EXPORTING handle = w_hdl command = w_cmd compress = 'N' TABLES data = it_cmdout EXCEPTIONS tcpip_error = 1 command_error = 2 data_error = 3 OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. REFRESH it_cmdout. CLEAR w_cmd. w_cmd = 'ls'. CALL FUNCTION 'FTP_COMMAND' EXPORTING handle = w_hdl command = w_cmd compress = 'N' TABLES data = it_cmdout EXCEPTIONS tcpip_error = 1 command_error = 2 data_error = 3 OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. *All customized checks for file to be placed here. LOOP AT it_cmdout INTO wa_cmdout FROM 4. *Check the command line for a file CHECK wa_cmdout-line+68(4) EQ '.txt'. *Move all the files to the FTP table wa_iplftp-file_nm = wa_cmdout-line+39(33). wa_iplftp-log_id = w_logid. *Currently the transfer date/time will be taken wa_iplftp-fdate = sy-datum."WA_CMDOUT-LINE+39(8). wa_iplftp-ftime = sy-uzeit."WA_CMDOUT-LINE+48(6). wa_iplftp-ernam = sy-uname. APPEND wa_iplftp TO it_iplftp. ENDLOOP. REFRESH it_cmdout. ENDFORM. " LOG_FILES *&--------------------------------------------------------------------- *& Form MOVE_FILES *&--------------------------------------------------------------------- FORM move_files . DATA : l_indx TYPE i. CLEAR w_cmd. CONCATENATE 'lcd' p_sap INTO w_cmd SEPARATED BY space. *Change the local directory to the sap inbound directory CALL FUNCTION 'FTP_COMMAND' EXPORTING handle = w_hdl command = w_cmd compress = 'N' TABLES data = it_cmdout EXCEPTIONS command_error = 1 tcpip_error = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. REFRESH it_cmdout. *Move each file from FTP to SAP inbound directory LOOP AT it_iplftp INTO wa_iplftp WHERE stat EQ space OR stat EQ 'CR'. l_indx = sy-tabix. CLEAR w_cmd. REFRESH it_cmdout. CONCATENATE 'get' wa_iplftp-file_nm INTO w_cmd SEPARATED BY space. CALL FUNCTION 'FTP_COMMAND' EXPORTING handle = w_hdl command = w_cmd compress = 'N' TABLES data = it_cmdout EXCEPTIONS command_error = 1 tcpip_error = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. READ TABLE it_cmdout INTO wa_cmdout INDEX 2. IF sy-subrc EQ 0. IF wa_cmdout-line CS 'command successful'. wa_iplftp-stat = 'CR'. wa_iplftp-mess = text-004. ELSE. wa_iplftp-stat = 'EF'. wa_iplftp-mess = text-005. ENDIF. ENDIF. MODIFY it_iplftp FROM wa_iplftp INDEX l_indx. *delete from FTP CLEAR w_cmd. CONCATENATE 'delete' wa_iplftp-file_nm INTO w_cmd SEPARATED BY space. CALL FUNCTION 'FTP_COMMAND' EXPORTING handle = w_hdl command = w_cmd compress = 'N' TABLES data = it_cmdout EXCEPTIONS command_error = 1 tcpip_error = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ENDLOOP. *Insert all table entries. INSERT ztbl_ipl_ftp FROM TABLE it_iplftp. IF sy-subrc NE 0. MESSAGE text-006 TYPE 'I'. ENDIF. ENDFORM. " MOVE_FILES *&--------------------------------------------------------------------- *& Form CLOSE_FTP *&--------------------------------------------------------------------- FORM close_ftp . CALL FUNCTION 'FTP_DISCONNECT' EXPORTING handle = w_hdl. CALL FUNCTION 'RFC_CONNECTION_CLOSE' EXPORTING destination = c_dest EXCEPTIONS OTHERS = 1. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ENDFORM. " CLOSE_FTP *&--------------------------------------------------------------------- *& Form DISP_RES *&--------------------------------------------------------------------- *Display the output *---------------------------------------------------------------------- FORM disp_res . DATA : l_layout TYPE slis_layout_alv. l_layout-colwidth_optimize = 'X'. *Display table contents of updated files CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY' EXPORTING i_callback_program = sy-repid i_structure_name = 'ZTBL_IPL_FTP' is_layout = l_layout TABLES t_outtab = it_iplftp EXCEPTIONS program_error = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ENDFORM. " DISP_RES
List of all pages
Pages at first level
Move a file from source to target directories or Delete file. I
Z_ARCH_MV command needs to be created in SM49 transaction for your operating system, to move file (mv command in Unix-like systems).
Selection texts to be created:
P_COPY | Copy |
P_DELE | Delete Source File |
P_MOVE | Move |
P_SFILE | Source File |
P_S_AS | Source Application Server |
P_S_PC | Source Presentation Server |
P_TFILE | Target File |
P_T_AS | Target Application Server |
P_T_PC | Target Presentation Server |
P_XFER | Transfer |
Messages used:
Message class | Number | Text |
---|---|---|
FI | 899 | &1 &2 &3 &4 |
REPORT Z_ARCH_MOVE NO STANDARD PAGE HEADING LINE-SIZE 132. ************************************************************************" * Move a file from source to target directories or Delete file * * This program will not run in a productive client. * * Source and target may be either on the Presentation or Application * servers. * * You can only copy if either source or target is on the Presentation * server. * You can either copy or move if both source and target are on the * Application server. * * When copying, provide the complete file specification for both * source and target. * * I had trouble getting the OS commands to accept an application server * filespec containing spaces. So there's a warning if you use one. Be * aware that the operation may not succeed regardless of the program * messages. * Tables ************************************************************************ ************************************************************************" * Types ************************************************************************" TYPE-POOLS: ABAP. TYPES : BEGIN OF TY_DATA, REC TYPE STRING, END OF TY_DATA. TYPES: TYT_DATA TYPE STANDARD TABLE OF TY_DATA. ************************************************************************ * Classes ************************************************************************" CLASS CL_GUI_FRONTEND_SERVICES DEFINITION LOAD. ************************************************************************ * Data ************************************************************************" DATA: W_ANSWER TYPE CHAR1, W_RC TYPE I. DATA: BEGIN OF W_FLAG, STOP TYPE FLAG, END OF W_FLAG. DATA: T_DATA TYPE TYT_DATA. ************************************************************************ * Selection screen ************************************************************************" * Customising - change the first block to reflect your requirements. * Set the "modif id" to "OUT" to make a field output-only * or to "HID" to hide it completely.* Data selections ***************** SELECTION-SCREEN: BEGIN OF BLOCK ZSELECTIONS WITH FRAME. * Action SELECTION-SCREEN: BEGIN OF BLOCK B1 WITH FRAME TITLE TEXT-001. * Move or Copy PARAMETERS: P_XFER RADIOBUTTON GROUP ZG1 DEFAULT 'X'. * Delete PARAMETERS: P_DELE RADIOBUTTON GROUP ZG1. SELECTION-SCREEN: END OF BLOCK B1. * Source SELECTION-SCREEN: BEGIN OF BLOCK B2 WITH FRAME TITLE TEXT-002. * Presentation server PARAMETERS: P_S_PC RADIOBUTTON GROUP ZG2 DEFAULT 'X'. * Application server PARAMETERS: P_S_AS RADIOBUTTON GROUP ZG2. * File name PARAMETERS: P_SFILE TYPE LOCALFILE. SELECTION-SCREEN: END OF BLOCK B2. * Target (Move or Copy only) SELECTION-SCREEN: BEGIN OF BLOCK B3 WITH FRAME TITLE TEXT-003. * Presentation server PARAMETERS: P_T_PC RADIOBUTTON GROUP ZG3. * Application server PARAMETERS: P_T_AS RADIOBUTTON GROUP ZG3 DEFAULT 'X'. * File name PARAMETERS: P_TFILE TYPE LOCALFILE. * Between Application servers SELECTION-SCREEN: BEGIN OF BLOCK B4 WITH FRAME TITLE TEXT-004. * Move PARAMETERS: P_MOVE RADIOBUTTON GROUP ZG4 DEFAULT 'X'. * Copy PARAMETERS: P_COPY RADIOBUTTON GROUP ZG4. SELECTION-SCREEN: END OF BLOCK B4. SELECTION-SCREEN: END OF BLOCK B3. SELECTION-SCREEN: END OF BLOCK ZSELECTIONS. ************************************************************************ * Events ************************************************************************" INITIALIZATION. PERFORM NOT_IN_PRODUCTION. AT SELECTION-SCREEN ON BLOCK ZSELECTIONS. PERFORM CHECK_SELECTIONS. AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_SFILE. PERFORM CHOOSE_FILENAME USING 'P_SFILE' 'P_S_PC'. AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_TFILE. PERFORM CHOOSE_FILENAME USING 'P_TFILE' 'P_T_PC'. START-OF-SELECTION. PERFORM DETERMINE_ACTIONS. END-OF-SELECTION. PERFORM STOP_IF_REQUESTED. ************************************************************************ * Forms ************************************************************************" ************************************************************************ FORM CHECK_SELECTIONS. ************************************************************************" DATA: L_TEMPFILE TYPE LOCALFILE. * Need a source file IF P_SFILE IS INITIAL. MESSAGE E899(FI) WITH 'Source must be specified'. ENDIF. * Need a target file for Move or Copy IF P_XFER EQ ABAP_TRUE AND P_TFILE IS INITIAL. MESSAGE E899(FI) WITH 'Target must be specified'. ENDIF. * Check for spaces in source or target IF P_S_AS EQ ABAP_TRUE. L_TEMPFILE = P_SFILE. CONDENSE L_TEMPFILE NO-GAPS. IF L_TEMPFILE NE P_SFILE. MESSAGE W899(FI) WITH 'Spaces in source file name'. ENDIF. ENDIF. IF P_T_AS EQ ABAP_TRUE. L_TEMPFILE = P_TFILE. CONDENSE L_TEMPFILE NO-GAPS. IF L_TEMPFILE NE P_TFILE. MESSAGE W899(FI) WITH 'Spaces in target file name'. ENDIF. ENDIF. ENDFORM. "check_selections ************************************************************************ FORM CHOOSE_FILENAME USING PX_FIELD_FILENAME LIKE DYNPREAD-FIELDNAME PX_FIELD_PCFLAG LIKE DYNPREAD-FIELDNAME. ************************************************************************" DATA: L_LOCATION LIKE DXFIELDS-LOCATION. DATA: LT_DYNP TYPE STANDARD TABLE OF DYNPREAD, L_DYNP TYPE DYNPREAD. L_DYNP-FIELDNAME = PX_FIELD_PCFLAG. APPEND L_DYNP TO LT_DYNP. CALL FUNCTION 'DYNP_VALUES_READ' EXPORTING DYNAME = SY-CPROG DYNUMB = SY-DYNNR TABLES DYNPFIELDS = LT_DYNP EXCEPTIONS OTHERS = 11. IF SY-SUBRC <> 0. MESSAGE E899(FI) WITH 'Error (1) reading selection screen'. ENDIF. READ TABLE LT_DYNP INDEX 1 INTO L_DYNP. IF SY-SUBRC EQ 0. IF L_DYNP-FIELDVALUE EQ ABAP_TRUE. L_LOCATION = 'P'. ELSE. L_LOCATION = 'A'. ENDIF. ELSE. MESSAGE E899(FI) WITH 'Error (2) reading selection screen'. ENDIF. CALL FUNCTION 'F4_DXFILENAME_4_DYNP' EXPORTING DYNPFIELD_FILENAME = PX_FIELD_FILENAME DYNAME = SY-CPROG DYNUMB = SY-DYNNR FILETYPE = 'P' LOCATION = L_LOCATION SERVER = ' '. ENDFORM. "choose_filename ************************************************************************ FORM CONFIRM_DELETE_FILE. ************************************************************************" CALL FUNCTION 'POPUP_TO_CONFIRM' EXPORTING TEXT_QUESTION = 'Do you really want to delete this file?' DISPLAY_CANCEL_BUTTON = ABAP_FALSE IMPORTING ANSWER = W_ANSWER EXCEPTIONS TEXT_NOT_FOUND = 1 OTHERS = 2. IF SY-SUBRC NE 0 OR W_ANSWER NE 1. W_FLAG-STOP = ABAP_TRUE. MESSAGE S899(FI) WITH 'Deletion not attempted'. STOP. ENDIF. ENDFORM. "confirm_delete_file ************************************************************************ FORM COPY_FILE_ON_PRES_SRVR USING PX_SOURCE TYPE LOCALFILE PX_TARGET TYPE LOCALFILE. ************************************************************************" DATA: L_SFILE TYPE STRING, L_TFILE TYPE STRING. L_SFILE = PX_SOURCE. L_TFILE = PX_TARGET. CALL METHOD CL_GUI_FRONTEND_SERVICES=>FILE_COPY EXPORTING SOURCE = L_SFILE DESTINATION = L_TFILE OVERWRITE = ABAP_TRUE EXCEPTIONS OTHERS = 13. IF SY-SUBRC EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully copied file', PX_SOURCE, / 'to', PX_TARGET UNDER PX_SOURCE. ELSE. W_FLAG-STOP = ABAP_TRUE. MESSAGE S899(FI) WITH 'Failed to copy file' PX_SOURCE DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "copy_file_on_pres_srvr ************************************************************************ FORM DELETE_FILE. ************************************************************************" DATA: L_FILE TYPE STRING. IF P_S_PC EQ ABAP_TRUE. * Delete Presentation server file L_FILE = P_SFILE. CALL METHOD CL_GUI_FRONTEND_SERVICES=>FILE_DELETE EXPORTING FILENAME = L_FILE CHANGING RC = W_RC EXCEPTIONS FILE_DELETE_FAILED = 1 CNTL_ERROR = 2 ERROR_NO_GUI = 3 FILE_NOT_FOUND = 4 ACCESS_DENIED = 5 UNKNOWN_ERROR = 6 NOT_SUPPORTED_BY_GUI = 7 WRONG_PARAMETER = 8 OTHERS = 9. ELSE. * Delete Application server file CATCH SYSTEM-EXCEPTIONS FILE_ACCESS_ERRORS = 4. DELETE DATASET P_SFILE. ENDCATCH. ENDIF. IF SY-SUBRC EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully deleted file', P_SFILE. ELSE. W_FLAG-STOP = ABAP_TRUE. MESSAGE S899(FI) WITH 'Failed to delete file' P_SFILE DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "delete_file ************************************************************************ FORM DETERMINE_ACTIONS. ************************************************************************" IF P_XFER EQ ABAP_TRUE. PERFORM MOVE_OR_COPY. ELSE. PERFORM CONFIRM_DELETE_FILE. PERFORM DELETE_FILE. ENDIF. ENDFORM. "determine_actions ************************************************************************ FORM MOVE_FILE_ON_APP_SRVR USING PX_SOURCE TYPE LOCALFILE PX_TARGET TYPE LOCALFILE. ************************************************************************" DATA: L_EXITCODE TYPE BTCXPGEXIT, L_PARMS TYPE BTCXPGPAR, L_STATUS TYPE BTCXPGSTAT. DATA: LT_PROTOCOL TYPE STANDARD TABLE OF BTCXPM, L_PROTOCOL TYPE BTCXPM. CONCATENATE PX_SOURCE PX_TARGET INTO L_PARMS SEPARATED BY SPACE. * External command: * - Unix - mv * - Windows - cmd /c move CALL FUNCTION 'SXPG_COMMAND_EXECUTE' EXPORTING COMMANDNAME = 'Z_ARCH_MV' ADDITIONAL_PARAMETERS = L_PARMS IMPORTING STATUS = L_STATUS EXITCODE = L_EXITCODE TABLES EXEC_PROTOCOL = LT_PROTOCOL EXCEPTIONS NO_PERMISSION = 1 COMMAND_NOT_FOUND = 2 PARAMETERS_TOO_LONG = 3 SECURITY_RISK = 4 WRONG_CHECK_CALL_INTERFACE = 5 PROGRAM_START_ERROR = 6 PROGRAM_TERMINATION_ERROR = 7 X_ERROR = 8 PARAMETER_EXPECTED = 9 TOO_MANY_PARAMETERS = 10 ILLEGAL_COMMAND = 11 WRONG_ASYNCHRONOUS_PARAMETERS = 12 CANT_ENQ_TBTCO_ENTRY = 13 JOBCOUNT_GENERATION_ERROR = 14 OTHERS = 15. IF SY-SUBRC NE 0 OR L_STATUS NE 'O' OR L_EXITCODE NE '0'. * Failure FORMAT COLOR COL_NEGATIVE. WRITE: / 'Failed to move' , PX_SOURCE, / 'to', PX_TARGET UNDER PX_SOURCE. FORMAT COLOR COL_NORMAL. LOOP AT LT_PROTOCOL INTO L_PROTOCOL. WRITE: / L_PROTOCOL-MESSAGE+0(L_PROTOCOL-LENGTH). ENDLOOP. ELSE. * Success FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully moved' , PX_SOURCE, / 'to', PX_TARGET UNDER PX_SOURCE. ENDIF. ENDFORM. "move_file_on_app_srvr ************************************************************************ FORM MOVE_OR_COPY. ************************************************************************" IF P_S_AS EQ ABAP_TRUE AND P_T_AS EQ ABAP_TRUE. * Source and Target both on AppSrvr IF P_MOVE EQ ABAP_TRUE. PERFORM MOVE_FILE_ON_APP_SRVR USING P_SFILE P_TFILE. ELSE. PERFORM READ_APPSRVR_FILE USING P_SFILE CHANGING T_DATA. PERFORM WRITE_APPSRVR_FILE USING P_TFILE T_DATA. ENDIF. ELSEIF P_S_PC EQ ABAP_TRUE AND P_T_PC EQ ABAP_TRUE. * Source and Target both on PresSrvr PERFORM COPY_FILE_ON_PRES_SRVR USING P_SFILE P_TFILE. ELSEIF P_S_PC EQ ABAP_TRUE. * Source on PresSrvr; Target on AppSrvr PERFORM READ_LOCAL_FILE USING P_SFILE CHANGING T_DATA. PERFORM WRITE_APPSRVR_FILE USING P_TFILE T_DATA. ELSE. * Source on AppSrvr; Target on PresSrvr PERFORM READ_APPSRVR_FILE USING P_SFILE CHANGING T_DATA. PERFORM WRITE_LOCAL_FILE USING P_TFILE T_DATA. ENDIF. ENDFORM. "move_or_copy ************************************************************************ FORM NOT_IN_PRODUCTION. ************************************************************************" DATA: L_CCCATEGORY TYPE CCCATEGORY. SELECT SINGLE CCCATEGORY INTO L_CCCATEGORY FROM T000 WHERE MANDT EQ SY-MANDT. IF L_CCCATEGORY EQ 'P'. MESSAGE E899(FI) WITH 'Program' SY-REPID 'is not available in Production clients'. ENDIF. ENDFORM. "not_in_production ************************************************************************ FORM READ_APPSRVR_FILE USING PX_SOURCE TYPE LOCALFILE CHANGING PXT_DATA TYPE TYT_DATA. ************************************************************************" DATA: L_DATA TYPE TY_DATA. CATCH SYSTEM-EXCEPTIONS FILE_ACCESS_ERRORS = 4. OPEN DATASET PX_SOURCE FOR INPUT IN TEXT MODE ENCODING DEFAULT. DO. READ DATASET PX_SOURCE INTO L_DATA-REC. IF SY-SUBRC NE 0. EXIT. ENDIF. APPEND L_DATA TO PXT_DATA. ENDDO. CLOSE DATASET PX_SOURCE. ENDCATCH. IF SY-SUBRC EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully read', PX_SOURCE. FORMAT COLOR COL_NORMAL. ELSE. W_FLAG-STOP = ABAP_TRUE. MESSAGE S899(FI) WITH 'Unable to read AppSrvr file' PX_SOURCE DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "read_appsrvr_file ************************************************************************ FORM READ_LOCAL_FILE USING PX_SOURCE TYPE LOCALFILE CHANGING PXT_DATA TYPE TYT_DATA. ************************************************************************ DATA: L_FILE TYPE STRING. L_FILE = PX_SOURCE. CALL FUNCTION 'GUI_UPLOAD' EXPORTING FILENAME = L_FILE TABLES DATA_TAB = PXT_DATA EXCEPTIONS OTHERS = 17. IF SY-SUBRC EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully read', PX_SOURCE. FORMAT COLOR COL_NORMAL. ELSE. W_FLAG-STOP = ABAP_TRUE. MESSAGE S899(FI) WITH 'Unable to read local file' PX_SOURCE DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "read_local_file ************************************************************************ FORM STOP_IF_REQUESTED. ************************************************************************ IF W_FLAG-STOP EQ ABAP_TRUE. STOP. ENDIF. ENDFORM. "stop_if_requested ************************************************************************ FORM WRITE_APPSRVR_FILE USING PX_TARGET TYPE LOCALFILE PXT_DATA TYPE TYT_DATA. ************************************************************************ DATA: L_DATA TYPE TY_DATA. CATCH SYSTEM-EXCEPTIONS FILE_ACCESS_ERRORS = 4. OPEN DATASET PX_TARGET FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. LOOP AT PXT_DATA INTO L_DATA. TRANSFER L_DATA-REC TO PX_TARGET. ENDLOOP. CLOSE DATASET PX_TARGET. ENDCATCH. IF SY-SUBRC EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully written', PX_TARGET. FORMAT COLOR COL_NORMAL. ELSE. W_FLAG-STOP = ABAP_TRUE. MESSAGE S899(FI) WITH 'Unable to write AppSrvr file' PX_TARGET DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "write_appsrvr_file ************************************************************************ FORM WRITE_LOCAL_FILE USING PX_TARGET TYPE LOCALFILE PXT_DATA TYPE TYT_DATA. ************************************************************************" DATA: L_FILE TYPE STRING. L_FILE = PX_TARGET. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING FILENAME = L_FILE TABLES DATA_TAB = PXT_DATA EXCEPTIONS OTHERS = 17. IF SY-SUBRC EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully written', PX_TARGET. FORMAT COLOR COL_NORMAL. ELSE. W_FLAG-STOP = ABAP_TRUE. MESSAGE S899(FI) WITH 'Unable to write local file' PX_TARGET DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "write_local_file
This piece of code will help in uploading and downloading .txt or .csv files from application server to presentation server and vice versa.
*Text symbols: *001 File Handling *002 Path *003 YES *004 NO *Selection Texts: *P_CG3Y Download *P_CG3Z Upload *P_FILE Presentation Server Path *P_FILE1 Presentation Server Path *P_O_WRIT Overwrite the file ? *P_PATH Application Server Path *P_PATH1 Application Server Path *&---------------------------------------------------------------------* *& Report Z_CG3_Z_Y *& *&---------------------------------------------------------------------* *& *& *&---------------------------------------------------------------------* REPORT z_cg3_z_y NO STANDARD PAGE HEADING. CONSTANTS : c_m1(2) TYPE c VALUE 'M1', c_m2(2) TYPE c VALUE 'M2', c_m3(2) TYPE c VALUE 'M3', c_m4(2) TYPE c VALUE 'M4', c_x(1) TYPE c VALUE 'X'. DATA : w_path TYPE sapb-sappfad, w_file TYPE sapb-sappfad. DATA w_ans(1) TYPE c. DATA : BEGIN OF t_data OCCURS 0, data(3000) TYPE c, END OF t_data. SELECTION-SCREEN : BEGIN OF BLOCK ss01 WITH FRAME TITLE text-001. PARAMETERS : p_cg3z RADIOBUTTON GROUP g1 USER-COMMAND flag DEFAULT 'X' , p_cg3y RADIOBUTTON GROUP g1 . SELECTION-SCREEN : BEGIN OF BLOCK ss02 WITH FRAME TITLE text-002. PARAMETERS : p_file TYPE rlgrap-filename DEFAULT 'D:\test.csv' MODIF ID m1. PARAMETERS : p_path TYPE rlgrap-filename DEFAULT '/tmp/test' MODIF ID m1. PARAMETERS : p_path1(60) TYPE c DEFAULT '/tmp/test' MODIF ID m2. PARAMETERS : p_file1 TYPE rlgrap-filename DEFAULT 'D:\test.txt' MODIF ID m2. SELECTION-SCREEN : END OF BLOCK ss02. SKIP 2. SELECTION-SCREEN : BEGIN OF LINE. SELECTION-SCREEN : POSITION 60. PARAMETERS : p_o_writ AS CHECKBOX MODIF ID m1. SELECTION-SCREEN: COMMENT 62(15) text1 MODIF ID m1. SELECTION-SCREEN : END OF LINE. SELECTION-SCREEN : END OF BLOCK ss01. AT SELECTION-SCREEN OUTPUT. LOOP AT SCREEN. IF p_cg3z EQ c_x AND screen-group1 EQ c_m2. screen-active = 0. ENDIF. IF p_cg3y EQ c_x AND screen-group1 EQ c_m1. screen-active = 0. ENDIF. MODIFY SCREEN. ENDLOOP. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. DATA: t_file_tab TYPE filetable, w1 LIKE LINE OF t_file_tab, w_rc TYPE i. CALL METHOD cl_gui_frontend_services=>file_open_dialog EXPORTING default_extension = 'CSV' CHANGING file_table = t_file_tab rc = w_rc EXCEPTIONS file_open_dialog_failed = 1 cntl_error = 2 error_no_gui = 3 not_supported_by_gui = 4 OTHERS = 5. IF sy-subrc = 0. * MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno * WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. READ TABLE t_file_tab INTO w1 INDEX 1. IF sy-subrc = 0. p_file = w1-filename. ENDIF. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file1. DATA: t_file_tab TYPE filetable, w1 LIKE LINE OF t_file_tab, w_rc TYPE i. CALL METHOD cl_gui_frontend_services=>file_open_dialog EXPORTING default_extension = 'CSV' CHANGING file_table = t_file_tab rc = w_rc EXCEPTIONS file_open_dialog_failed = 1 cntl_error = 2 error_no_gui = 3 not_supported_by_gui = 4 OTHERS = 5. IF sy-subrc = 0. * MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno * WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. READ TABLE t_file_tab INTO w1 INDEX 1. IF sy-subrc = 0. p_file1 = w1-filename. ENDIF. INITIALIZATION . text1 = 'Overwrite File'. START-OF-SELECTION. IF p_cg3z EQ c_x. TRANSLATE : p_path TO LOWER CASE, p_path1 TO LOWER CASE, p_file TO LOWER CASE, p_file1 TO LOWER CASE. IF p_o_writ EQ ' '. OPEN DATASET p_path FOR INPUT IN BINARY MODE. IF sy-subrc EQ 0. CLEAR : w_ans. CALL FUNCTION 'POPUP_TO_CONFIRM' EXPORTING titlebar = 'CONFIRMATION POP-UP ' text_question = 'Are You Sure You WAnt to Over Write The File' text_button_1 = 'YES' text_button_2 = 'NO' display_cancel_button = c_x start_column = 25 start_row = 6 IMPORTING answer = w_ans. IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. IF w_ans = '1'. CLOSE DATASET p_path. PERFORM f_upload_download . ELSEIF w_ans = '2'. CLOSE DATASET p_path. EXIT. ELSEIF w_ans = 'A'. CLOSE DATASET p_path. EXIT. ENDIF. ELSE. CLOSE DATASET p_path. PERFORM f_upload_download . w_ans = '1'. ENDIF. CLOSE DATASET p_path. ELSE. PERFORM f_upload_download . ENDIF. ELSE. " for dwonload p_cg3y PERFORM f_upload_download . ENDIF. IF p_cg3z EQ c_x. DATA : w_filename TYPE string. MOVE p_file TO w_filename. CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = w_filename TABLES data_tab = t_data. IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. ELSE. TRANSLATE p_path1 TO LOWER CASE. OPEN DATASET p_path1 FOR INPUT IN TEXT MODE ENCODING DEFAULT. DO. IF sy-subrc <> 0. EXIT. ENDIF. READ DATASET p_path1 INTO t_data . APPEND t_data. CLEAR t_data. ENDDO. CLOSE DATASET p_path1. ENDIF. END-OF-SELECTION. IF w_ans EQ '1' OR p_o_writ EQ 'X'. WRITE : / 'File contents:'. SKIP 1. LOOP AT t_data. WRITE : t_data-data. ENDLOOP. ENDIF. *&---------------------------------------------------------------------* *& Form F_UPLOAD_DOWNLOAD *&---------------------------------------------------------------------* FORM f_upload_download . IF p_cg3z EQ c_x. TRANSLATE p_path TO LOWER CASE. MOVE p_path TO w_path . MOVE p_file TO w_file. CALL FUNCTION 'ARCHIVFILE_CLIENT_TO_SERVER' EXPORTING path = w_file targetpath = w_path EXCEPTIONS error_file = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ELSE . MESSAGE 'successfully transfered' TYPE 'S'. ENDIF. ELSE. TRANSLATE : p_path1 TO LOWER CASE, p_file1 TO LOWER CASE. MOVE p_path1 TO w_path . MOVE p_file1 TO w_file. CALL FUNCTION 'ARCHIVFILE_SERVER_TO_CLIENT' EXPORTING path = w_path targetpath = w_file EXCEPTIONS error_file = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ELSE. MESSAGE 'successfully transfered' TYPE 'S' . ENDIF. ENDIF. ENDFORM. " F_UPLOAD_DOWNLOAD
Use the Function :
C13Z_APPL_TO_FRONT_END to download the data from the Application server to Presentation.
This has to be restricted due to the functionality for the user can download any file to PC. So the file name has to be checked to restrict the user downloading any file to his PC.
Kind Regards,
Senthilraj Selvaraj
Author: Raghavendra AY
Submitted: February 15, 2007
Since it's not possible to download data to presentation server in background, we first download the data to application server file, then read this application server file and save it to presentation server in foreground, which ideally means each such download program requires another program which takes the file structure into consideration and download it to presentation server.
This code can be used to download data from files on application server to presentation server in foreground
To download data from Application server files to presentation server
Upload / Download / Delete functionality of Application server Program.
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'REPORT zapplserver MESSAGE-ID fb. ************************************************************************ * Constants CONSTANTS:c_mask(80) TYPE c VALUE ',.,..', " Mask c_file_type(10) TYPE c VALUE 'ASC', " File type c_mode(1) TYPE c VALUE 'L'. " Mode * Internal tables * DATA: BEGIN OF i_file OCCURS 0, field(3000) TYPE c, END OF i_file. DATA : v_msg(100), struct_file LIKE i_file OCCURS 0. * Parameters PARAMETERS: p_fpath TYPE draw-filep OBLIGATORY, p_lpath TYPE localfile, p_upload AS CHECKBOX DEFAULT 'X', p_dload AS CHECKBOX, p_delete AS CHECKBOX. ************************************************************************ * Check selection-screen entries * ************************************************************************ * At selection screen AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_lpath. PERFORM get_file CHANGING p_lpath. ************************************************************************ * Main * ************************************************************************ * Start of selection START-OF-SELECTION. IF p_upload = 'X'. * Upload to app server PERFORM upload_to_appserver. ENDIF. IF p_dload = 'X'. * Download to desktop PERFORM download_to_desktop. ENDIF. IF p_delete = 'X'. * Delete file on app server DELETE DATASET p_fpath. IF sy-subrc = 0. MESSAGE s000 WITH 'File deleted'. ENDIF. ENDIF. ************************************************************************ * OUTPUT of extracted data * ************************************************************************ * sort. * loop. * * endloop. ************************************************************************ * EVENTS DURING LISTPROCESSING * ************************************************************************ ************************************************************************ * EVENTS AT USER COMMAND ************************************************************************ *at line selection. *at user-command. ************************************************************************ * ROUTINES/FORM * ************************************************************************ *------------------------------------------------------------- * Set file path of local machine *------------------------------------------------------------- FORM get_file CHANGING file_out. DATA: l_filename TYPE localfile. "Local file for upload/download CALL FUNCTION 'WS_FILENAME_GET' EXPORTING mask = c_mask mode = c_mode IMPORTING filename = l_filename EXCEPTIONS inv_winsys = 01 no_batch = 02 selection_cancel = 03 selection_error = 04. p_lpath = l_filename. ENDFORM. "get_file *&---------------------------------------------------------------------* *& Form UPLOAD_TO_APPSERVER *&---------------------------------------------------------------------* * Upload local file to app server *----------------------------------------------------------------------* FORM upload_to_appserver . DATA: l_lpath TYPE string. l_lpath = p_lpath. REFRESH i_file. CLEAR i_file. CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = l_lpath filetype = c_file_type TABLES data_tab = i_file EXCEPTIONS file_open_error = 1 file_read_error = 2 no_batch = 3 gui_refuse_filetransfer = 4 invalid_type = 5 no_authority = 6 unknown_error = 7 bad_data_format = 8 header_not_allowed = 9 separator_not_allowed = 10 header_too_long = 11 unknown_dp_error = 12 access_denied = 13 dp_out_of_memory = 14 disk_full = 15 dp_timeout = 16 OTHERS = 17. OPEN DATASET p_fpath FOR OUTPUT IN TEXT MODE ENCODING DEFAULT MESSAGE v_msg. IF sy-subrc = 0. LOOP AT i_file. " into struct_file. IF NOT i_file IS INITIAL. TRANSFER i_file TO p_fpath. ENDIF. ENDLOOP. ELSE. MESSAGE e000 WITH 'File cannot be opened for output'. ENDIF. CLOSE DATASET p_fpath. ENDFORM. " UPLOAD_TO_APPSERVER *&---------------------------------------------------------------------* *& Form DOWNLOAD_TO_DESKTOP *&---------------------------------------------------------------------* FORM download_to_desktop . OPEN DATASET p_fpath FOR INPUT IN TEXT MODE ENCODING DEFAULT MESSAGE v_msg. IF sy-subrc = 0. REFRESH : i_file. DO. READ DATASET p_fpath INTO i_file. IF sy-subrc = 0. APPEND i_file TO i_file. ELSE. EXIT. ENDIF. ENDDO. ELSE. MESSAGE e000 WITH 'File cannot be opened'. ENDIF. CLOSE DATASET p_fpath. CALL FUNCTION 'DOWNLOAD' EXPORTING filename = p_lpath TABLES data_tab = i_file. ENDFORM. " DOWNLOAD_TO_DESKTOP
REPORT z_arch_move NO STANDARD PAGE HEADING LINE-SIZE 132. ************************************************************************ * Move a file from source to target directories or Delete file * * This program will not run in a productive client. * * Source and target may be either on the Presentation or Application * servers. * * You can only copy if either source or target is on the Presentation * server. * You can either copy or move if both source and target are on the * Application server. * * When copying, provide the complete file specification for both * source and target. * * I had trouble getting the OS commands to accept an application server * filespec containing spaces. So there's a warning if you use one. Be * aware that the operation may not succeed regardless of the program * messages. ************************************************************************ * Tables ************************************************************************ ************************************************************************ * Types ************************************************************************ TYPE-POOLS: abap. TYPES: BEGIN OF ty_data, rec TYPE string, END OF ty_data. TYPES: tyt_data TYPE STANDARD TABLE OF ty_data. ************************************************************************ * Classes ************************************************************************ CLASS cl_gui_frontend_services DEFINITION LOAD. ************************************************************************ * Data ************************************************************************ DATA: w_answer TYPE char1, w_rc TYPE i. DATA: BEGIN OF w_flag, stop TYPE flag, END OF w_flag. DATA: t_data TYPE tyt_data. ************************************************************************ * Selection screen ************************************************************************ * Customising - change the first block to reflect your requirements. * Set the "modif id" to "OUT" to make a field output-only * or to "HID" to hide it completely. * Data selections ***************** SELECTION-SCREEN: BEGIN OF BLOCK zselections WITH FRAME. * Action SELECTION-SCREEN: BEGIN OF BLOCK b1 WITH FRAME TITLE text-001. * Move or Copy PARAMETERS: p_xfer RADIOBUTTON GROUP zg1 DEFAULT 'X'. * Delete PARAMETERS: p_dele RADIOBUTTON GROUP zg1. SELECTION-SCREEN: END OF BLOCK b1. * Source SELECTION-SCREEN: BEGIN OF BLOCK b2 WITH FRAME TITLE text-002. * Presentation server PARAMETERS: p_s_pc RADIOBUTTON GROUP zg2 DEFAULT 'X'. * Application server PARAMETERS: p_s_as RADIOBUTTON GROUP zg2. * File name PARAMETERS: p_sfile TYPE localfile. SELECTION-SCREEN: END OF BLOCK b2. * Target (Move or Copy only) SELECTION-SCREEN: BEGIN OF BLOCK b3 WITH FRAME TITLE text-003. * Presentation server PARAMETERS: p_t_pc RADIOBUTTON GROUP zg3. * Application server PARAMETERS: p_t_as RADIOBUTTON GROUP zg3 DEFAULT 'X'. * File name PARAMETERS: p_tfile TYPE localfile. * Between Application servers SELECTION-SCREEN: BEGIN OF BLOCK b4 WITH FRAME TITLE text-004. * Move PARAMETERS: p_move RADIOBUTTON GROUP zg4 DEFAULT 'X'. * Copy PARAMETERS: p_copy RADIOBUTTON GROUP zg4. SELECTION-SCREEN: END OF BLOCK b4. SELECTION-SCREEN: END OF BLOCK b3. SELECTION-SCREEN: END OF BLOCK zselections. ************************************************************************ * Events ************************************************************************ INITIALIZATION. PERFORM not_in_production. AT SELECTION-SCREEN ON BLOCK zselections. PERFORM check_selections. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_sfile. PERFORM choose_filename USING 'P_SFILE' 'P_S_PC'. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_tfile. PERFORM choose_filename USING 'P_TFILE' 'P_T_PC'. START-OF-SELECTION. PERFORM determine_actions. END-OF-SELECTION. PERFORM stop_if_requested. ************************************************************************ * Forms ************************************************************************ ************************************************************************ FORM check_selections. ************************************************************************ DATA: l_tempfile TYPE localfile. * Need a source file IF p_sfile IS INITIAL. MESSAGE e899(fi) WITH 'Source must be specified'. ENDIF. * Need a target file for Move or Copy IF p_xfer EQ abap_true AND p_tfile IS INITIAL. MESSAGE e899(fi) WITH 'Target must be specified'. ENDIF. * Check for spaces in source or target IF p_s_as EQ abap_true. l_tempfile = p_sfile. CONDENSE l_tempfile NO-GAPS. IF l_tempfile NE p_sfile. MESSAGE w899(fi) WITH 'Spaces in source file name'. ENDIF. ENDIF. IF p_t_as EQ abap_true. l_tempfile = p_tfile. CONDENSE l_tempfile NO-GAPS. IF l_tempfile NE p_tfile. MESSAGE w899(fi) WITH 'Spaces in target file name'. ENDIF. ENDIF. ENDFORM. "check_selections ************************************************************************ FORM choose_filename USING px_field_filename LIKE dynpread-fieldname px_field_pcflag LIKE dynpread-fieldname. ************************************************************************ DATA: l_location LIKE dxfields-location. DATA: lt_dynp TYPE STANDARD TABLE OF dynpread, l_dynp TYPE dynpread. l_dynp-fieldname = px_field_pcflag. APPEND l_dynp TO lt_dynp. CALL FUNCTION 'DYNP_VALUES_READ' EXPORTING dyname = sy-cprog dynumb = sy-dynnr TABLES dynpfields = lt_dynp EXCEPTIONS OTHERS = 11. IF sy-subrc <> 0. MESSAGE e899(fi) WITH 'Error (1) reading selection screen'. ENDIF. READ TABLE lt_dynp INDEX 1 INTO l_dynp. IF sy-subrc EQ 0. IF l_dynp-fieldvalue EQ abap_true. l_location = 'P'. ELSE. l_location = 'A'. ENDIF. ELSE. MESSAGE e899(fi) WITH 'Error (2) reading selection screen'. ENDIF. CALL FUNCTION 'F4_DXFILENAME_4_DYNP' EXPORTING dynpfield_filename = px_field_filename dyname = sy-cprog dynumb = sy-dynnr filetype = 'P' location = l_location server = ' '. ENDFORM. "choose_filename ************************************************************************ FORM confirm_delete_file. ************************************************************************ CALL FUNCTION 'POPUP_TO_CONFIRM' EXPORTING text_question = 'Do you really want to delete this file?' display_cancel_button = abap_false IMPORTING answer = w_answer EXCEPTIONS text_not_found = 1 OTHERS = 2. IF sy-subrc NE 0 OR w_answer NE 1. w_flag-stop = abap_true. MESSAGE s899(fi) WITH 'Deletion not attempted'. STOP. ENDIF. ENDFORM. "confirm_delete_file ************************************************************************ FORM copy_file_on_pres_srvr USING px_source TYPE localfile px_target TYPE localfile. ************************************************************************ DATA: l_sfile TYPE string, l_tfile TYPE string. l_sfile = px_source. l_tfile = px_target. CALL METHOD cl_gui_frontend_services=>file_copy EXPORTING source = l_sfile destination = l_tfile overwrite = abap_true EXCEPTIONS OTHERS = 13. IF sy-subrc EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully copied file', px_source, / 'to', px_target UNDER px_source. ELSE. w_flag-stop = abap_true. MESSAGE s899(fi) WITH 'Failed to copy file' px_source DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "copy_file_on_pres_srvr ************************************************************************ FORM delete_file. ************************************************************************ DATA: l_file TYPE string. IF p_s_pc EQ abap_true. * Delete Presentation server file l_file = p_sfile. CALL METHOD cl_gui_frontend_services=>file_delete EXPORTING filename = l_file CHANGING rc = w_rc EXCEPTIONS file_delete_failed = 1 cntl_error = 2 error_no_gui = 3 file_not_found = 4 access_denied = 5 unknown_error = 6 not_supported_by_gui = 7 wrong_parameter = 8 OTHERS = 9. ELSE. * Delete Application server file CATCH SYSTEM-EXCEPTIONS file_access_errors = 4. DELETE DATASET p_sfile. ENDCATCH. ENDIF. IF sy-subrc EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully deleted file', p_sfile. ELSE. w_flag-stop = abap_true. MESSAGE s899(fi) WITH 'Failed to delete file' p_sfile DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "delete_file ************************************************************************ FORM determine_actions. ************************************************************************ IF p_xfer EQ abap_true. PERFORM move_or_copy. ELSE. PERFORM confirm_delete_file. PERFORM delete_file. ENDIF. ENDFORM. "determine_actions ************************************************************************ FORM move_file_on_app_srvr USING px_source TYPE localfile px_target TYPE localfile. ************************************************************************ DATA: l_exitcode TYPE btcxpgexit, l_parms TYPE btcxpgpar, l_status TYPE btcxpgstat. DATA: lt_protocol TYPE STANDARD TABLE OF btcxpm, l_protocol TYPE btcxpm. CONCATENATE px_source px_target INTO l_parms SEPARATED BY space. * External command: * - Unix - mv * - Windows - cmd /c move CALL FUNCTION 'SXPG_COMMAND_EXECUTE' EXPORTING commandname = 'Z_ARCH_MV' additional_parameters = l_parms IMPORTING status = l_status exitcode = l_exitcode TABLES exec_protocol = lt_protocol EXCEPTIONS no_permission = 1 command_not_found = 2 parameters_too_long = 3 security_risk = 4 wrong_check_call_interface = 5 program_start_error = 6 program_termination_error = 7 x_error = 8 parameter_expected = 9 too_many_parameters = 10 illegal_command = 11 wrong_asynchronous_parameters = 12 cant_enq_tbtco_entry = 13 jobcount_generation_error = 14 OTHERS = 15. IF sy-subrc NE 0 OR l_status NE 'O' OR l_exitcode NE '0'. * Failure FORMAT COLOR COL_NEGATIVE. WRITE: / 'Failed to move' , px_source, / 'to', px_target UNDER px_source. FORMAT COLOR COL_NORMAL. LOOP AT lt_protocol INTO l_protocol. WRITE: / l_protocol-message+0(l_protocol-length). ENDLOOP. ELSE. * Success FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully moved' , px_source, / 'to', px_target UNDER px_source. ENDIF. ENDFORM. "move_file_on_app_srvr ************************************************************************ FORM move_or_copy. ************************************************************************ IF p_s_as EQ abap_true AND p_t_as EQ abap_true. * Source and Target both on AppSrvr IF p_move EQ abap_true. PERFORM move_file_on_app_srvr USING p_sfile p_tfile. ELSE. PERFORM read_appsrvr_file USING p_sfile CHANGING t_data. PERFORM write_appsrvr_file USING p_tfile t_data. ENDIF. ELSEIF p_s_pc EQ abap_true AND p_t_pc EQ abap_true. * Source and Target both on PresSrvr PERFORM copy_file_on_pres_srvr USING p_sfile p_tfile. ELSEIF p_s_pc EQ abap_true. * Source on PresSrvr; Target on AppSrvr PERFORM read_local_file USING p_sfile CHANGING t_data. PERFORM write_appsrvr_file USING p_tfile t_data. ELSE. * Source on AppSrvr; Target on PresSrvr PERFORM read_appsrvr_file USING p_sfile CHANGING t_data. PERFORM write_local_file USING p_tfile t_data. ENDIF. ENDFORM. "move_or_copy ************************************************************************ FORM not_in_production. ************************************************************************ DATA: l_cccategory TYPE cccategory. SELECT SINGLE cccategory INTO l_cccategory FROM t000 WHERE mandt EQ sy-mandt. IF l_cccategory EQ 'P'. MESSAGE e899(fi) WITH 'Program' sy-repid 'is not available in Production clients'. ENDIF. ENDFORM. "not_in_production ************************************************************************ FORM read_appsrvr_file USING px_source TYPE localfile CHANGING pxt_data TYPE tyt_data. ************************************************************************ DATA: l_data TYPE ty_data. CATCH SYSTEM-EXCEPTIONS file_access_errors = 4. OPEN DATASET px_source FOR INPUT IN TEXT MODE. DO. READ DATASET px_source INTO l_data-rec. IF sy-subrc NE 0. EXIT. ENDIF. APPEND l_data TO pxt_data. ENDDO. CLOSE DATASET px_source. ENDCATCH. IF sy-subrc EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully read', px_source. FORMAT COLOR COL_NORMAL. ELSE. w_flag-stop = abap_true. MESSAGE s899(fi) WITH 'Unable to read AppSrvr file' px_source DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "read_appsrvr_file ************************************************************************ FORM read_local_file USING px_source TYPE localfile CHANGING pxt_data TYPE tyt_data. ************************************************************************ DATA: l_file TYPE string. l_file = px_source. CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = l_file TABLES data_tab = pxt_data EXCEPTIONS OTHERS = 17. IF sy-subrc EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully read', px_source. FORMAT COLOR COL_NORMAL. ELSE. w_flag-stop = abap_true. MESSAGE s899(fi) WITH 'Unable to read local file' px_source DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "read_local_file ************************************************************************ FORM stop_if_requested. ************************************************************************ IF w_flag-stop EQ abap_true. STOP. ENDIF. ENDFORM. "stop_if_requested ************************************************************************ FORM write_appsrvr_file USING px_target TYPE localfile pxt_data TYPE tyt_data. ************************************************************************ DATA: l_data TYPE ty_data. CATCH SYSTEM-EXCEPTIONS file_access_errors = 4. OPEN DATASET px_target FOR OUTPUT IN TEXT MODE. LOOP AT pxt_data INTO l_data. TRANSFER l_data-rec TO px_target. ENDLOOP. CLOSE DATASET px_target. ENDCATCH. IF sy-subrc EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully written', px_target. FORMAT COLOR COL_NORMAL. ELSE. w_flag-stop = abap_true. MESSAGE s899(fi) WITH 'Unable to write AppSrvr file' px_target DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "write_appsrvr_file ************************************************************************ FORM write_local_file USING px_target TYPE localfile pxt_data TYPE tyt_data. ************************************************************************ DATA: l_file TYPE string. l_file = px_target. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = l_file TABLES data_tab = pxt_data EXCEPTIONS OTHERS = 17. IF sy-subrc EQ 0. FORMAT COLOR COL_POSITIVE. WRITE: / 'Successfully written', px_target. FORMAT COLOR COL_NORMAL. ELSE. w_flag-stop = abap_true. MESSAGE s899(fi) WITH 'Unable to write local file' px_target DISPLAY LIKE 'E'. STOP. ENDIF. ENDFORM. "write_local_file
REPORT z_appl_presentation_server NO STANDARD PAGE HEADING . *&----------------DATA DECLARATION----------------------------------& INCLUDE z_appl_presentation_server_data_declaration. *&----------------INCLUDE FOR PERFORMS------------------------------&* INCLUDE z_appl_presentation_server_forms. *&----------------AT SELECTION SCREEN EVENT-------------------------&* *& At selection screen output for screen attributes AT SELECTION-SCREEN OUTPUT. PERFORM screen_attributes. *& Providing f4 help path to filmanager on presentation server AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. PERFORM source_destination. *& Providing f4 help path to Application server AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file1. PERFORM application_server_path. *&----------------START OF SELECTION--------------------------------&* START-OF-SELECTION. *& Reading data from application server and copy it to presentation server IF p_read = 'X'. PERFORM read_from_server. *& Copy the data from presentation server and write to application server ELSE. PERFORM write_to_server. ENDIF. *&---------------------------------------------------------------------* *& Include z_appl_presentation_server_DATA_DECLARATION *&---------------------------------------------------------------------* *& Types Declaration TYPES : BEGIN OF ty_bseg, "Accounting Document Segment bukrs(4), "Company Code belnr(10), "Accounting Document Number gjahr(4), "Fiscal Year buzei(3), "Number of Line Item Within Accounting Document kostl(10), "Cost Center saknr(10), "G/L Account No END OF ty_bseg. *& Work area and Internal tabel DATA: wa_bseg TYPE ty_bseg, it_bseg TYPE STANDARD TABLE OF ty_bseg. *& Data declaratio for read/write data to application serve DATA: d_filename(128), file TYPE string. *& Selection Screen PARAMETERS: p_read RADIOBUTTON GROUP rad1 DEFAULT 'X' "Copy the file from Application server to PC USER-COMMAND chek, p_write RADIOBUTTON GROUP rad1, "Copy the file from PC to Application server p_file LIKE rlgrap-filename OBLIGATORY DEFAULT 'C:\Documents and Settings\pvora\Desktop\test.txt' MODIF ID g02, "Filename on PC p_file1 LIKE rlgrap-filename DEFAULT '.\Pratik.txt' "Filename on server MODIF ID g01. *&---------------------------------------------------------------------* *& Include z_appl_presentation_server_FORMS *&---------------------------------------------------------------------* *&---------------------------------------------------------------------* *& Form read_from_server *&---------------------------------------------------------------------* FORM read_from_server. CLEAR d_filename. d_filename = p_file1. *& Reading file from application server OPEN DATASET d_filename FOR INPUT IN TEXT MODE ENCODING DEFAULT. DO. READ DATASET d_filename INTO wa_bseg. IF sy-subrc <> 0. EXIT. ENDIF. APPEND wa_bseg TO it_bseg. ENDDO. CLOSE DATASET d_filename. *& Dwonloading file to Presentation Server file = p_file. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = file filetype = 'ASC' append = ' ' TABLES data_tab = it_bseg EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21. ENDFORM. " read_from_server *&---------------------------------------------------------------------* *& Form write_to_server *&---------------------------------------------------------------------* FORM write_to_server. *& Uploading file from Presentation server file = p_file. CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = file filetype = 'ASC' TABLES data_tab = it_bseg EXCEPTIONS file_open_error = 1 file_read_error = 2 no_batch = 3 gui_refuse_filetransfer = 4 invalid_type = 5 no_authority = 6 unknown_error = 7 bad_data_format = 8 header_not_allowed = 9 separator_not_allowed = 10 header_too_long = 11 unknown_dp_error = 12 access_denied = 13 dp_out_of_memory = 14 disk_full = 15 dp_timeout = 16. CLEAR d_filename. d_filename = p_file1. *& Writing in the file on application server OPEN DATASET d_filename FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. LOOP AT it_bseg INTO wa_bseg. TRANSFER wa_bseg TO d_filename. ENDLOOP. CLOSE DATASET d_filename. OPEN DATASET d_filename FOR INPUT IN TEXT MODE ENCODING DEFAULT. DO. READ DATASET d_filename INTO wa_bseg. IF sy-subrc <> 0. EXIT. ENDIF. WRITE:/ wa_bseg-bukrs, wa_bseg-belnr, wa_bseg-gjahr, wa_bseg-kostl, wa_bseg-saknr. ENDDO. CLOSE DATASET d_filename. ENDFORM. " write_to_server *&---------------------------------------------------------------------* *& Form source_destination *&---------------------------------------------------------------------* FORM source_destination. file = p_file. CALL FUNCTION 'KD_GET_FILENAME_ON_F4' EXPORTING program_name = syst-repid dynpro_number = syst-dynnr field_name = p_file * STATIC = ' ' * MASK = ' ' CHANGING file_name = p_file EXCEPTIONS mask_too_long = 1. ENDFORM. " source_destination *&---------------------------------------------------------------------* *& Form application_server_path *&---------------------------------------------------------------------* FORM application_server_path. IF p_read = 'X'. *& Selecting file from server on pressing f4 CALL FUNCTION '/SAPDMC/LSM_F4_SERVER_FILE' EXPORTING directory = '.\' filemask = ' ' IMPORTING serverfile = p_file1 EXCEPTIONS canceled_by_user = 1. ELSE. MESSAGE 'F4 is only valid for transfering data from Server to PC' TYPE 'S'. ENDIF. ENDFORM. " application_server_path *&---------------------------------------------------------------------* *& Form screen_attributes *&---------------------------------------------------------------------* FORM screen_attributes . IF p_write = 'X'. LOOP AT SCREEN. IF screen-group1 = 'G01'. screen-input = 0. MODIFY SCREEN. ENDIF. ENDLOOP. ELSE. LOOP AT SCREEN. IF screen-group1 = 'G02'. screen-input = 0. MODIFY SCREEN. ENDIF. ENDLOOP. ENDIF. ENDFORM. " screen_attributes
File on presentation server
Solution for any ABAP system
Parameters of F4_DXFILENAME_4_DYNP:
filetype:
'P' represents Physical file name
'L' represents Logical file name.
location:
'A' represents Application Server
'P' represents Presentation server.
PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. CALL FUNCTION 'F4_DXFILENAME_4_DYNP' EXPORTING dynpfield_filename = 'P_FILE' dyname = sy-repid dynumb = sy-dynnr filetype = 'P' location = 'A' server = ' '.
Solution for SAP ERP only
With the function module F4_FILENAME.
REPORT zvenkattest. *------------------------------------------------------------* * selection screen parameters *------------------------------------------------------------* PARAMETERS: p_source LIKE rlgrap-filename. *------------------------------------------------------------* * at selection screen for field *------------------------------------------------------------* AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_source . CALL FUNCTION 'F4_FILENAME' EXPORTING program_name = syst-cprog dynpro_number = syst-dynnr field_name = 'P_SOURCE' IMPORTING file_name = p_source.
File on application server
Parameters of F4_DXFILENAME_4_DYNP:
filetype:
'P' represents Physical file name
'L' represents Logical file name.
location:
'A' represents Application Server
'P' represents Presentation server.
PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. CALL FUNCTION 'F4_DXFILENAME_4_DYNP' EXPORTING dynpfield_filename = 'P_FILE' dyname = sy-repid dynumb = sy-dynnr filetype = 'P' location = 'A' server = ' '.
Get Name of Files in Excel File from Selected Directory of Local System
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'REPORT zfsl_gdirfn. ************************************************************************ * Declaration of Variables & Internal Tables * ************************************************************************ DATA: it_file LIKE STANDARD TABLE OF sdokpath WITH HEADER LINE, it_dir LIKE STANDARD TABLE OF sdokpath WITH HEADER LINE, file_count TYPE i, dir_count TYPE i. ************************************************************************ * Selection Screen * ************************************************************************ SELECTION-SCREEN: BEGIN OF BLOCK a WITH FRAME TITLE ftitle, BEGIN OF LINE, COMMENT 1(40) lpdirp FOR FIELD pdirp. PARAMETER: pdirp TYPE pfeflnamel OBLIGATORY. " Directory Path from where you want to get Name of Files SELECTION-SCREEN: END OF LINE, BEGIN OF LINE, COMMENT 1(40) lpsavep FOR FIELD psavep. PARAMETER: psavep TYPE string OBLIGATORY. " Excel File Path and Name in which you want to Save Name of Files SELECTION-SCREEN: END OF LINE, END OF BLOCK a. ************************************************************************ * START-OF-SELECTION * ************************************************************************ START-OF-SELECTION. CALL FUNCTION 'TMP_GUI_DIRECTORY_LIST_FILES' " To Get the Name of Files in Internal Table of Given Directory EXPORTING directory = pdirp filter = '*.*' IMPORTING file_count = file_count " Number of File in Directory dir_count = dir_count " Number of Directory in Directory TABLES file_table = it_file " Table for Name of Files dir_table = it_dir " Table for Name of Directories EXCEPTIONS cntl_error = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. IF file_count IS NOT INITIAL. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = psavep " Path and Name of Excel File with Extension .xls TABLES data_tab = it_file " Internal Table having all Name of Files EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. ELSE. MESSAGE: 'No file found in the selected Directory' TYPE 'I'. ENDIF. ************************************************************************ * INITIALIZATION * ************************************************************************ INITIALIZATION. ftitle = 'Select from the following Options'. lpdirp = 'Directory of Fiels'. lpsavep = 'Path and Name of Excel File'. pdirp = 'C:\'. psavep = 'C:\test.xls'. ************************************************************************ * AT SELECTION-SCREEN ON VALUE-REQUEST * ************************************************************************ *F4 for Getting Directory Path AT SELECTION-SCREEN ON VALUE-REQUEST FOR pdirp. DATA: fname TYPE string. CALL METHOD cl_gui_frontend_services=>directory_browse EXPORTING window_title = 'Select Directory' CHANGING selected_folder = fname EXCEPTIONS cntl_error = 1 error_no_gui = 2 not_supported_by_gui = 3 OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. pdirp = fname. *F4 for Getting File Path and Name AT SELECTION-SCREEN ON VALUE-REQUEST FOR psavep. DATA: filename TYPE string, path TYPE string. CALL METHOD cl_gui_frontend_services=>file_save_dialog EXPORTING window_title = 'Select path and file name' default_extension = 'XLS' CHANGING filename = filename path = path fullpath = psavep EXCEPTIONS cntl_error = 1 error_no_gui = 2 not_supported_by_gui = 3 OTHERS = 4. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
Introduction
SAP has provided us with a lot of standard programs to make our day to day life easier. The standard code suite extends from simple programs to upload or download hierarchies to more complex ones to activate inactive objects in production. The flat file manipulation programs include programs to upload or download flat file to or from the system. But this list does not include one to transpose a flat file.
There are ‘n’ numbers of ways to achieve this. What is given in this article is to consider the separator values e.g. comma (,) or colon (;) as regular expressions and derive the values nested within the separators.
Regular Expressions
In computing, a regular expression provides a concise and flexible means for "matching" (specifying and recognizing) strings of text, such as particular characters, words, or patterns of characters - Wikipedia
For a general overview about regular expressions: Regular Expression
Generally, in a given string any value that occurs repeatedly, be it in regular or random intervals, can be termed as a regular expression. In our case, any flat-file whose values are separated by an expression e.g. comma (,) or colon (;) can be taken to contain regular expressions with the separator as the expression itself.
REGEX
The REGEX command was introduced into ABAP with NetWeaver Release 2004s. It has been widely used for manipulating character strings and to search for specific expressions in text files which are extensive.
A code sample for finding regular expression would be like,
FIND ALL OCCURRENCES OF REGEX <expression> IN <string> RESULTS <t_results>.
The above code would execute the REGEX command over the given string and store all occurrences of the ‘expression’ in an internal table
Note: A regular ‘csv’ file would not have a comma separator at the end of a record. An entry would be manually inserted in the program to identify the last value.
CODE
*&---------------------------------------------------------------------* *& Report ZFILE_TRANSPOSE *& *&---------------------------------------------------------------------* REPORT zfile_transpose. *DECLARATION TYPES: BEGIN OF st_file, rec TYPE string, END OF st_file. TYPES: BEGIN OF st_inter, row_no TYPE i, rec TYPE string, END OF st_inter. DATA : t_file TYPE TABLE OF st_file, "Internal table to read file wa_file TYPE st_file, t_outfile TYPE TABLE OF st_file, wa_outfile TYPE st_file, t_inter TYPE TABLE OF st_inter, "Intermidiate table to store file wa_inter TYPE st_inter. FIELD-SYMBOLS : <fs_file> TYPE st_file. FIELD-SYMBOLS : <fs_inter> TYPE st_inter. DATA : it_csv TYPE match_result_tab, "Internal table for REGEX result wa_it_csv LIKE LINE OF it_csv. DATA : col_count TYPE i, row_count TYPE i, loop_count1 TYPE i, loop_count2 TYPE i, col_len TYPE i, temp1 TYPE i, temp2 TYPE i, temp3 TYPE i, value TYPE string, char_len TYPE string. CONSTANTS: c_filetype TYPE char10 VALUE 'ASC'. "For Filetype DAT PARAMETERS: p_file1 LIKE rlgrap-filename OBLIGATORY. "Get file loacftion PARAMETERS: p_file2 LIKE rlgrap-filename OBLIGATORY. "File loaction for transposed data PARAMETERS: p_sptr TYPE c OBLIGATORY. "Character used for separator AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file1. "Get FILE from selection screen *GET FILE PATH PERFORM get_file_path USING p_file1. *&---------------------------------------------------------------------* START-OF-SELECTION. *UPLOAD DATA PERFORM get_data USING p_file1 CHANGING t_file. "Copy FILE data to internal table *&---------------------------------------------------------------------* *CREATE INTERNAL TABLE TO STORE DTO DETAILS READ TABLE t_file INTO wa_file INDEX 1. IF sy-subrc = 0. FIND ALL OCCURRENCES OF p_sptr IN wa_file-rec MATCH COUNT col_count. col_count = col_count + 1. "To count number of columns ENDIF. LOOP AT t_file INTO wa_file. row_count = row_count + 1. "To count number of rows ENDLOOP. LOOP AT t_file INTO wa_file. loop_count1 = sy-tabix. col_len = strlen( wa_file-rec ). "Find length of each row FIND ALL OCCURRENCES OF REGEX p_sptr IN wa_file-rec RESULTS it_csv. IF sy-subrc = 0. wa_it_csv-offset = col_len. "Create entry in regex table APPEND wa_it_csv TO it_csv. "for last comma ELSE. MESSAGE 'Incorrect Separator Value' TYPE 'E'. ENDIF. temp1 = 0. LOOP AT it_csv INTO wa_it_csv. temp2 = temp3 = wa_it_csv-offset. temp2 = temp2 - temp1. value = wa_file-rec+temp1(temp2). "Get value between commas temp1 = temp3 + 1. loop_count2 = sy-tabix. IF loop_count1 = 1. wa_inter-row_no = loop_count2. "Include row number for each record CONCATENATE value p_sptr INTO wa_inter-rec. APPEND wa_inter TO t_inter. ENDIF. IF loop_count1 > 1 AND loop_count1 < row_count. "Adding comma separation to transposed value READ TABLE t_inter ASSIGNING <fs_inter> WITH KEY row_no = loop_count2. IF sy-subrc = 0. CONCATENATE <fs_inter>-rec value p_sptr INTO <fs_inter>-rec. UNASSIGN <fs_inter>. ENDIF. ELSEIF loop_count1 EQ row_count. "No comma needed for last value READ TABLE t_inter ASSIGNING <fs_inter> WITH KEY row_no = loop_count2. IF sy-subrc = 0. CONCATENATE <fs_inter>-rec value INTO <fs_inter>-rec. UNASSIGN <fs_inter>. ENDIF. ENDIF. ENDLOOP. ENDLOOP. LOOP AT t_inter INTO wa_inter. wa_outfile-rec = wa_inter-rec. APPEND wa_outfile TO t_outfile. ENDLOOP. *DOWNLOAD DATA PERFORM put_data USING p_file2 CHANGING t_outfile. "Copy FILE data to internal table IF sy-subrc = 0. MESSAGE 'File transposed Succesfully' TYPE 'S'. ENDIF. *&---------------------------------------------------------------------* *& Form GET_FILE_PATH *&---------------------------------------------------------------------* FORM get_file_path USING p_p_file1. DATA : wsl_upfile LIKE rlgrap-filename VALUE IS INITIAL. wsl_upfile = p_file1. CLEAR: p_file1. CALL FUNCTION 'KD_GET_FILENAME_ON_F4' EXPORTING PROGRAM_NAME = SYST-REPID DYNPRO_NUMBER = SYST-DYNNR CHANGING file_name = wsl_upfile EXCEPTIONS MASK_TOO_LONG = 1 OTHERS = 2. p_file1 = wsl_upfile. ENDFORM. " GET_FILE_PATH *&---------------------------------------------------------------------* *& Form GET_DATA *&---------------------------------------------------------------------* FORM get_data USING p_p_file1 CHANGING p_t_file TYPE table. DATA: l_file TYPE string. l_file = p_p_file1. CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = l_file filetype = c_filetype TABLES data_tab = p_t_file EXCEPTIONS file_open_error = 1 file_read_error = 2 no_batch = 3 gui_refuse_filetransfer = 4 invalid_type = 5 no_authority = 6 unknown_error = 7 bad_data_format = 8 header_not_allowed = 9 separator_not_allowed = 10 header_too_long = 11 unknown_dp_error = 12 access_denied = 13 dp_out_of_memory = 14 disk_full = 15 dp_timeout = 16 OTHERS = 17. IF sy-subrc IS INITIAL. ELSE. MESSAGE s001(00) WITH 'File not found'. STOP. ENDIF. CLEAR l_file. ENDFORM. " GET_DATA *&---------------------------------------------------------------------* *& Form PUT_DATA *&---------------------------------------------------------------------* FORM put_data USING p_p_file2 CHANGING p_t_outfile TYPE table. DATA: l_outfile TYPE string. l_outfile = p_p_file2. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = l_outfile filetype = c_filetype TABLES data_tab = p_t_outfile EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. * Implement suitable error handling here ENDIF. ENDFORM. " PUT_DATA
Author: Sujeet Mishra
Submitted: 22/8/2013
Description
CALL METHOD cl_gui_frontend_services=>execute EXPORTING document = 'C:\Documents and Settings\xyz\Desktop\hi.txt' * application = * parameter = * default_directory = * maximized = * minimized = * synchronous = * operation = 'OPEN' EXCEPTIONS cntl_error = 1 error_no_gui = 2 bad_parameter = 3 file_not_found = 4 path_not_found = 5 file_extension_unknown = 6 error_execute_failed = 7 synchronous_failed = 8 not_supported_by_gui = 9 others = 10 . IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF.
In SAP6.0, certain function modules have become obsolete. They need to be replaced by new function modules. Here I describe how to handle two of the most important function modules used to download/upload files from server - UPLOAD/ DOWNLOAD. These function modules have been replaced by GUI_UPLOAD/GUI_DOWNLOAD in 6.0. So when upgrading , we need to pay special attention while replacing the old function modules with the new ones as the data dypes and certain other parameters have changed. For example, in DOWNLOAD/UPLOAD function modules, a pop up screen used to appear which asked for the location of the file to be uploaded or downloaded. But the functionality is missing in the replacement fms. So in order to restore the previous functionality, we need to call a class method cl_gui_frontend_services=>file_open_dialog (for upload functionality) and cl_gui_frontend_services=>file_save_dialog (for download functionality) which gives the pop up.
Following code snippet shows how the replacement can be implemented.
DOWNLOAD ::
CALL FUNCTION 'DOWNLOAD' EXPORTING filename = p_out1 "' ' filetype = 'ASC' item = 'Hierarchy'(t17) silent = 'M' col_select = 'X' TABLES data_tab = t_output.
Replaced with ::
DATA: l_p_out1_new TYPE string, l_filename TYPE string, l_fullpath TYPE string, l_path TYPE string. MOVE p_out1 TO l_p_out1_new . CALL METHOD cl_gui_frontend_services=>file_save_dialog EXPORTING default_file_name = l_p_out1_new CHANGING filename = l_filename path = l_path fullpath = l_fullpath. IF sy-subrc <> 0. ENDIF. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = l_fullpath filetype = 'ASC' append = 'X' TABLES data_tab = t_output EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
UPLOAD ::
CALL FUNCTION 'UPLOAD' EXPORTING codepage = ' ' filename = 'H:\data\BI-TEST.txt' filetype = 'DAT' TABLES data_tab = <p1> EXCEPTIONS conversion_error = 1 invalid_table_width = 2 invalid_type = 3 no_batch = 4 unknown_error = 5 gui_refuse_filetransfer = 6 OTHERS = 7.
Replaced with ::
DATA:lt_file_table TYPE filetable. DATA:lw_file TYPE file_table. DATA:l_rc TYPE i. DATA:BEGIN OF lt_itab OCCURS 0 , l_c1 TYPE string, END OF lt_itab. DATA:l_action TYPE i. DATA l_filename_new TYPE string . CALL METHOD cl_gui_frontend_services=>file_open_dialog EXPORTING default_filename = 'H:TEST.TXT' CHANGING file_table = lt_file_table rc = l_rc user_action = l_action. IF l_action NE 9. READ TABLE lt_file_table INTO lw_file INDEX 1. l_filename_new = lw_file-filename. *Upload FM Replaced with Gui_upload CALL FUNCTION 'GUI_UPLOAD' EXPORTING codepage = '' filename = l_filename_new filetype = 'ASC' has_field_separator = 'X' TABLES data_tab = <p1> EXCEPTIONS no_batch = 4 invalid_type = 3 unknown_error = 5 OTHERS = 7. . IF sy-subrc <> 0. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. ENDIF.
Description : There are instances, when some garbage characters creep into the data while reading from a text file ( .txt ) in application server. It may get the upload totoaly wrong and can give incoorect results during execution. Heres a simple snippet to uplaod data from application server into SAP internal Table without any garbage characters in the data. The only thing to be kept in mind is that it works on for text files (.txt)
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'FIELD-SYMBOLS: <fs> TYPE x_upload. FIELD-SYMBOLS: <fs_struc> TYPE any. FIELD-SYMBOLS: <fs_itab> TYPE table. DATA :l_sys_cp LIKE tcp00-cpcodepage. DATA : l_tcp00 LIKE tcp00. DATA : l_lan_cp LIKE tcp00-cpcodepage. * check code page first CALL FUNCTION 'SYSTEM_CODEPAGE' IMPORTING codepage = l_sys_cp. SELECT SINGLE * FROM tcp00 INTO l_tcp00 WHERE cpcodepage = l_sys_cp. CONSTANTS :c_rc4 LIKE sy-subrc VALUE 4. CALL FUNCTION 'SCP_CODEPAGE_FOR_LANGUAGE' EXPORTING language = sy-langu IMPORTING codepage = l_lan_cp EXCEPTIONS OTHERS = c_rc4. IF sy-subrc <> 0. l_lan_cp = l_sys_cp. ENDIF. DATA : i_tab_input_data TYPE truxs_t_text_data. ASSIGN i_tab_input_data[] TO <fs_itab>. ASSIGN LOCAL COPY OF INITIAL LINE OF <fs_itab> TO <fs_struc>. OPEN DATASET p_upload FOR INPUT IN TEXT MODE ENCODING DEFAULT. "also check the option of ... CODE PAGE cp in help WHILE sy-subrc = 0. READ DATASET p_upload INTO <fs_struc>. APPEND <fs_struc> TO <fs_itab>. ENDWHILE. CLOSE DATASET p_upload. DATA: ld_lan_cp TYPE abap_encod. ld_lan_cp = l_lan_cp. CALL FUNCTION 'TRANSLATE_CODEPAGE_IN' EXPORTING codepage_from = ld_lan_cp TABLES t_data = <fs_itab> EXCEPTIONS OTHERS = 0. DATA: l_file_name_string TYPE string, l_file_format_10 TYPE char10. l_file_name_string = p_upload. l_file_format_10 = 'ASC'. CONSTANTS : c_rc0 LIKE sy-subrc VALUE 0, c_rc8 LIKE sy-subrc VALUE 8, c_rc12 LIKE sy-subrc VALUE 12, c_rc16 LIKE sy-subrc VALUE 16. DATA : l_totalsize TYPE i. DATA : l_fm_name LIKE tfdir-funcname. DATA : l_tfdir LIKE tfdir. DATA : i_line_header TYPE char01. l_fm_name = 'TEXT_CONVERT_TXT_TO_SAP'. SELECT SINGLE * FROM tfdir INTO l_tfdir WHERE funcname = l_fm_name. IF sy-subrc = 0. CALL FUNCTION l_fm_name EXPORTING i_fileformat = 'TXT' i_field_seperator = 'X' i_line_header = i_line_header i_tab_raw_data = <fs_itab> i_filename = p_upload i_totalsize = l_totalsize TABLES i_tab_converted_data = it_upload EXCEPTIONS OTHERS = c_rc4. ELSE. MESSAGE e046(fl) WITH l_fm_name RAISING conversion_failed. ENDIF. IF sy-subrc <> c_rc0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 RAISING conversion_failed. ENDIF.
TYPES : BEGIN OF gty_display, f1 TYPE char20, f2 TYPE char20, END OF gty_display. DATA: lv_filename TYPE rlgrap-filename, gs_display TYPE gty_display , lv_timestamp(55) TYPE c, gt_display TYPE gty_display, gt_final TYPE gty_display. CONSTANTS : lc_ex TYPE char4 VALUE '.XLS', gc_con_tab TYPE c VALUE cl_abap_char_utilities=>horizontal_tab. " p_path is where you need to store the file in SAP directory CONCATENATE p_path lc_ex INTO lv_timestamp. lv_filename = lv_timestamp. OPEN DATASET lv_filename FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. LOOP AT gt_display INTO gs_display. CONCATENATE gs_display-f1 gs_displayf2 INTO gt_final SEPARATED BY gc_con_tab. TRANSFER gt_final TO lv_filename. ENDLOOP. CLOSE DATASET lv_filename.
Author: Eswar Kanakanti
Submitted: 20-Apr-2007
Summary:
This is an ABAP program, downloads a file based on the user provided delimit characters on the selection screen dynamically.
In case of Tab delimit character, user has to provide 'T' so that program will create a tab delimit file.
Source Code:
REPORT zfile_with_delchar. TABLES: mara. *******Types Declaration TYPES: **--File Output BEGIN OF ty_out, line(150), END OF ty_out, **--Material Data BEGIN OF ty_mat, matnr TYPE mara-matnr, mtart TYPE mara-mtart, mbrsh TYPE mara-mbrsh, meins TYPE mara-meins, END OF ty_mat. DATA: it_out TYPE STANDARD TABLE OF ty_out WITH HEADER LINE, it_mat TYPE STANDARD TABLE OF ty_mat WITH HEADER LINE. **--Selection-screen Design SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001. **--Material numbers SELECT-OPTIONS s_matnr FOR mara-matnr. SELECTION-SCREEN BEGIN OF LINE. SELECTION-SCREEN COMMENT 1(15) text-002. **--Delimit char PARAMETERS: p_dchar TYPE c OBLIGATORY. SELECTION-SCREEN COMMENT 20(20) text-003. SELECTION-SCREEN END OF LINE. SELECTION-SCREEN END OF BLOCK b1. CLASS cl_abap_char_utilities DEFINITION LOAD. START-OF-SELECTION. **--Get the data from material table SELECT matnr mtart mbrsh meins FROM mara INTO TABLE it_mat WHERE matnr IN s_matnr. **--Prepare output file with specified delimit char LOOP AT it_mat. IF p_dchar = 'T'. CONCATENATE it_mat-matnr it_mat-mtart it_mat-mbrsh it_mat-meins INTO it_out-line SEPARATED BY cl_abap_char_utilities=>horizontal_tab. ELSE. CONCATENATE it_mat-matnr it_mat-mtart it_mat-mbrsh it_mat-meins INTO it_out-line SEPARATED BY p_dchar. ENDIF. APPEND it_out. CLEAR: it_out,it_mat. ENDLOOP. **--Download the data CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = 'C:\mat.txt' TABLES data_tab = it_out EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc = 0. WRITE:/ 'File is downloaded'. ENDIF.
Selection-screen:
Author: Vijay Babu Dudla
Submitted: 11.08.2008
Description: This report is used to Convert the Internal table to HTML formated table.
'WWW_ITAB_TO_HTML_HEADERS' "This is used to Set the Column properties
'WWW_ITAB_TO_HTML_LAYOUT' "This is used to set the layout properties
'WWW_ITAB_TO_HTML' "Using the Columns Definitions and Internal table this Function converts the internal table data into HTML format.
REPORT zdownload_table_html. *-Internal table Declaration TYPES: BEGIN OF ty_vbap, vbeln TYPE vbeln, posnr TYPE posnr, matnr TYPE matnr, END OF ty_vbap. *-ALL related Declarations DATA: t_header TYPE STANDARD TABLE OF w3head WITH HEADER LINE, "Header t_fields TYPE STANDARD TABLE OF w3fields WITH HEADER LINE, "Fields t_html TYPE STANDARD TABLE OF w3html, wa_header TYPE w3head, w_head TYPE w3head. DATA: it_vbap TYPE STANDARD TABLE OF ty_vbap, it_fcat TYPE lvc_t_fcat WITH HEADER LINE. START-OF-SELECTION. SELECT vbeln posnr matnr FROM vbap INTO TABLE it_vbap UP TO 20 ROWS. END-OF-SELECTION. *-Populate the Columns it_fcat-coltext = 'SalesOrder'. APPEND it_fcat. it_fcat-coltext = 'ItmeNumber'. APPEND it_fcat. it_fcat-coltext = 'Material'. APPEND it_fcat. *-Fill the Column heading and Filed Properties LOOP AT it_fcat. w_head-text = it_fcat-coltext. CALL FUNCTION 'WWW_ITAB_TO_HTML_HEADERS' EXPORTING field_nr = sy-tabix text = w_head-text fgcolor = 'black' bgcolor = 'green' TABLES header = t_header. CALL FUNCTION 'WWW_ITAB_TO_HTML_LAYOUT' EXPORTING field_nr = sy-tabix fgcolor = 'black' size = '3' TABLES fields = t_fields. ENDLOOP. *-Title of the Display wa_header-text = 'Sales Order Details' . wa_header-font = 'Arial'. wa_header-size = '2'. *-Preparing the HTML from Intenal Table REFRESH t_html. CALL FUNCTION 'WWW_ITAB_TO_HTML' EXPORTING table_header = wa_header TABLES html = t_html fields = t_fields row_header = t_header itable = it_vbap. *-Download the HTML into frontend CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = 'C:\Sales.htm' TABLES data_tab = t_html EXCEPTIONS file_write_error = 1 no_batch = 2 gui_refuse_filetransfer = 3 invalid_type = 4 no_authority = 5 unknown_error = 6 header_not_allowed = 7 separator_not_allowed = 8 filesize_not_allowed = 9 header_too_long = 10 dp_error_create = 11 dp_error_send = 12 dp_error_write = 13 unknown_dp_error = 14 access_denied = 15 dp_out_of_memory = 16 disk_full = 17 dp_timeout = 18 file_not_found = 19 dataprovider_exception = 20 control_flush_error = 21 OTHERS = 22. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF. *-Display the HTML file CALL METHOD cl_gui_frontend_services=>execute EXPORTING document = 'C:\Sales.htm' operation = 'OPEN' EXCEPTIONS cntl_error = 1 error_no_gui = 2 bad_parameter = 3 file_not_found = 4 path_not_found = 5 file_extension_unknown = 6 error_execute_failed = 7 synchronous_failed = 8 not_supported_by_gui = 9 OTHERS = 10. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.
REPORT z_zip_files_in_appsvr . DATA: lt_data TYPE TABLE OF x255, ls_data LIKE LINE OF lt_data. DATA: lv_zip_content TYPE xstring , lv_dsn1(100) VALUE '/sap/NSP/sys/test.as', lv_dsn2(100) VALUE '/sap/NSP/sys/test2.mxml', lv_dsn3(100) VALUE '/sap/NSP/sys/testarchive.zip', lv_file_length TYPE i , lv_content TYPE xstring, lo_zip TYPE REF TO cl_abap_zip. CREATE OBJECT lo_zip. * Read the data as a string CLEAR lv_content . OPEN DATASET lv_dsn1 FOR INPUT IN BINARY MODE. READ DATASET lv_dsn1 INTO lv_content . CLOSE DATASET lv_dsn1. lo_zip->add( name = 'test.as' content = lv_content ). CLEAR lv_content . OPEN DATASET lv_dsn2 FOR INPUT IN BINARY MODE. READ DATASET lv_dsn2 INTO lv_content . CLOSE DATASET lv_dsn2. lo_zip->add( name = 'test2.mxml' content = lv_content ). lv_zip_content = lo_zip->save( ). * Conver the xstring content to binary CALL FUNCTION 'SCMS_XSTRING_TO_BINARY' EXPORTING buffer = lv_zip_content IMPORTING output_length = lv_file_length TABLES binary_tab = lt_data. OPEN DATASET lv_dsn3 FOR OUTPUT IN BINARY MODE. LOOP AT lt_data INTO ls_data. TRANSFER ls_data TO lv_dsn3. ENDLOOP. CLOSE DATASET lv_dsn3.
Initial Author: Xinpeng Lin
Submitted: 11.9.2007
Other Authors: see Page History
This Code Snippets will clarify some general process of working with files when ABAP programming. Such as,Uploading/Downloading files from/to Application/Presentation server, adding F4 help to file path on the selection-screen,checking file existence.
Check File Existence
Before we process the file which is input on the selection screen by end-user, we need to check whether this file exists or not. If it does not exist, we just give an error message and need not to go into the main program .This logic should be done within the event 'AT SELECTION-SCREEN'.
presentation server file
For the presentation server file,here intruduce 2 ways, one is Function Module, the other is Class Static Method.
1. Using Funciton Moudle 'DX_FILE_EXISTENCE_CHECK'.
DATA: gdf_file_exist(1) TYPE c. PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN. CALL FUNCTION 'DX_FILE_EXISTENCE_CHECK' EXPORTING filename = p_file pc = 'X' * SERVER = IMPORTING file_exists = gdf_file_exist. IF NOT ( sy-subrc = 0 and gdf_file_exist = 'X' ) MESSAGE 'the input file does not exist.' TYPE 'E'. ENDIF.
Pay attention to the importing parameter 'pc', it should be set as 'X'.
2. Using Class Static Method 'CL_GUI_FRONTEND_SERVICES=>FILE_EXIST'
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'DATA: gdf_file_exist(1) TYPE c. PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN. CALL METHOD cl_gui_frontend_services=>file_exist EXPORTING file = p_file RECEIVING result = gdf_file_exist. IF NOT ( sy-subrc = 0 and gdf_file_exist = 'X' ) MESSAGE 'the input file does not exist.' TYPE 'E'. ENDIF.
application server file
Open it first within the event 'AT SELECTION-SCREEN'.If it can be opened successfully, this file exists. After open, do not forget to close it.
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN. OPEN DATASET p_file FOR INPUT IN TEXT MODE ENCODING DEFAULT. IF sy-subrc = 0. CLOSE DATASET p_file. ELSE. MESSAGE 'the input file does not exist.' TYPE 'E'. ENDIF.
Function Module 'OCS_GET_FILE_INFO'
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'DATA: gdt_ocs_file TYPE TABLE OF ocs_file. PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN. CALL FUNCTION 'OCS_GET_FILE_INFO' EXPORTING dir_name = p_file file_name = '*' TABLES dir_list = gdt_ocs_file.
Importing parameter 'file_name' is set as '*' means all the file in the specfied directory will be get and stored in the internal table 'gdt_ocs_file'. If the input file is included in the internal table, this file exists.
Add F4 Help
Adding one F4 Help to the file path on the selection-screen will be very helpful to the end-user.The logic should be under the event 'ON VALUE-REQUEST'.
presentation server file
For the presentation server file,here intruduce 2 ways, one is Function Module, the other is Class Static Method.
1. Using Function Module 'F4_FILENAME'.
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. CALL FUNCTION 'F4_FILENAME' * EXPORTING * PROGRAM_NAME = * DYNPRO_NUMBER = * FIELD_NAME = IMPORTING file_name = p_file.
2. Using Method 'CL_GUI_FRONTEND_SERVICES=>FILE_OPEN_DIALOG'.
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'DATA: gdt_filetable TYPE filetable. DATA: gdf_rc TYPE I. PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. CALL METHOD cl_gui_frontend_services=>file_open_dialog EXPORTING WINDOW_TITLE = 'Choose a file' CHANGING file_table = gdt_filetable rc = gdf_rc. IF sy-subrc = 0. READ TABLE gdt_filetable INTO gds_filetable INDEX 1. p_file = gds_filetable-filename. ENDIF.
gdf_rc is the number of selected file, if it is equal -1, error occured.
application server file
Generally it need not to provide F4 help for application server file. If we want it, there is also a Function Module which can be used.
PARAMETERS p_file TYPE dxfile-filename. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file. CALL FUNCTION 'F4_DXFILENAME_4_DYNP' EXPORTING dynpfield_filename = 'P_FILE' dyname = sy-repid dynumb = sy-dynnr filetype = 'P' location = 'A' server = ' '.
filetype: 'P' represents Physical file name; 'L' represents Logical file name.
location: 'A' represents Application Server; 'P' represents Presentation server.
Download Files
Sometimes we need to save the internal table data as a file for the further process.For download to presentation server and download to application server,they are 2 different kinds of process methods.
to presentation server
When storing internal table data as a local file on the presentation server, there are 2 methods we can use.
One is using the function modeule, the other is using the class static method.
1. Using Function Module 'GUI_DOWNLOAD'.
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'
DATA: gdf_filepath type dxfile-filename DATA: gdt_data type table of gts_data. START-OF-SELECTION. gdf_filepath = 'C:\mydata.txt'. CALL FUNCTION 'GUI_DOWNLOAD' EXPORTING filename = gdf_filepath filetype = 'ASC' write_field_separator = 'X' TABLES data_tab = gdt_data.
filetype is set by 'X' mens separating columns by Tabs in case of ASCII download.
If sy-subrc is equal 0, file downloading is successful.
2. Using class static method 'CL_GUI_FRONTEND_SERVICES =>GUI_DOWNLOAD'
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'DATA: gdf_filepath type dxfile-filename DATA: gdt_data type table of gts_data. START-OF-SELECTION. gdf_filepath = 'C:\mydata.txt'. CALL METHOD cl_gui_frontend_services=>gui_download EXPORTING filename = gdf_filepath filetype = 'ASC' write_field_separator = 'X' CHANGING data_tab = gdt_data.
filetype is set by 'X' mens separating columns by Tabs in case of ASCII download.
If sy-subrc is equal 0, file downloading is successful.
to application server
If we want to save the internal table data to the application server, there is no function module or class static method which we can use, we must write the code by ourselves.
1. no separator between field columns
DATA: gdf_filepath type dxfile-filename DATA: gdt_data type table of gts_data. DATA: ldf_length type i. FIELD-SYMBOLS: <lfs_outfile> TYPE gts_data START-OF-SELECTION. gdf_filepath = 'C:\mydata.txt'. OPEN DATASET gdf_filepath FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. LOOP AT prt_data ASSIGNING <lfs_outfile>. TRANSFER <lfs_outfile> TO prf_file. ENDLOOP. CLOSE DATASET gdf_filepath.
The prerequisite is the field of prt_data must be character type.
Using this method, every field column will output as the length defined,without separator.
2. tab separator between field columns
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'
DATA: gdf_filepath type dxfile-filename DATA: gdt_data type table of gts_data. DATA: ldf_length type i. FIELD-SYMBOLS: <lfs_outfile> TYPE gts_data START-OF-SELECTION. gdf_filepath = 'C:\mydata.txt'. OPEN DATASET gdf_filepath FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. LOOP AT prt_data ASSIGNING <lfs_outfile>. CONCATENATE <LFS_OUTFILE>-BUKRS <LFS_OUTFILE>-BUDAT ... INTO LDF_OUTDATA SEPARATED BY CL_ABAP_CHAR_UTILITIES=>HORIZONTAL_TAB. TRANSFER LDF_OUTDATA TO gdf_filepath. ENDLOOP. CLOSE DATASET gdf_filepath.
Upload Files
Sometimes we need to upload the file data to the internal table first, and then process it.For upload from presentation server and upload from application server,they are 2 different kinds of process methods.
from presentation server
When we upload a file data from presentation server to the internal table, there are 2 method that we can choose.One is using the Function Moduel, the other is using the class static method.
1. Using function module 'GUI_UPLOAD'
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'DATA: gdt_filedata TYPE TABLE OF gts_filedata. PARAMETERS p_file TYPE dxfile-filename. START-OF-SELECTION. CALL FUNCTION 'GUI_UPLOAD' EXPORTING filename = p_file has_field_separator = 'X' TABLES data_tab = gdt_filedata.
parameter has_field_separator is set as 'X' means columns separated by tabs in case of ASCII upload.
2. Using the method 'CL_GUI_FRONTEND_SERVICES =>GUI_UPLOAD'
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'DATA: gdt_filedata TYPE TABLE OF gts_filedata. PARAMETERS p_file TYPE dxfile-filename. START-OF-SELECTION. CALL METHOD cl_gui_frontend_services=>gui_upload EXPORTING filename = p_file has_field_separator = 'X' CHANGING data_tab = prt_table.
parameter 'has_field_separator' is set as 'X' means columns separated by tabs in case of ASCII upload.
from application server
If we want to upload file data from the application server to the internal table, there is no function module or class static method which we can use, we must wirte the code by ourselves.
1. no separator between field columns
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'PARAMETERS p_file TYPE dxfile-filename. START-OF-SELECTION. OPEN DATASET p_file IN TEXT MODE ENCODING DEFAULT FOR INPUT. DO. READ DATASET p_file INTO gds_data. IF sy-subrc <> 0. EXIT. ENDIF. APPEND gds_data TO gdt_data. ENDDO. CLOSE DATASET p_file.
2. tab separator between field columns
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'DATA: gds_field_split type gts_data. FIELD-SYMBOLS: <fs_field> TYPE gts_data. PARAMETERS p_file TYPE dxfile-filename. START-OF-SELECTION. OPEN DATASET prf_file IN TEXT MODE ENCODING DEFAULT FOR INPUT. DO. READ DATASET p_file INTO gds_field. SPLIT gds_field AT cl_abap_char_utilities=>horizontal_tab INTO TABLE gdt_field_split. LOOP AT gdt_field_split into gds_field_split. gdf_index = gdf_index + 1. ASSIGN COMPONENT gdf_index OF STRUCTURE gds_data to <fs_field>. IF sy-subrc = 0. <fs_field> = gds_field_split. ENDIF. ENDLOOP. APPEND gds_data TO gdt_data. ENDDO. CLOSE DATASET p_file.
This program doesn't do what it announces
DATA fname(60) VALUE 'myfile'. DATA: text1(12) VALUE 'abcdefghijkl', text2(5), leng TYPE i. OPEN DATASET fname FOR OUTPUT IN BINARY MODE. TRANSFER text1 TO fname. CLOSE DATASET fname. OPEN DATASET fname FOR INPUT IN BINARY MODE. DO. READ DATASET fname INTO text2 LENGTH leng. WRITE: / sy-subrc, text2, leng. IF sy-subrc <> 0. EXIT. ENDIF. ENDDO. CLOSE DATASET fname.
DATA fname(60) VALUE 'myfile'. DATA: text1(4) VALUE '1234 ', text2(8) VALUE '12345678', text3(2), leng TYPE i. OPEN DATASET fname FOR OUTPUT IN TEXT MODE. TRANSFER: text1 TO fname, text2 TO fname. CLOSE DATASET fname. OPEN DATASET fname FOR INPUT IN TEXT MODE. DO 2 TIMES. READ DATASET fname INTO text3 LENGTH leng. WRITE: / text3, leng. ENDDO. CLOSE DATASET fname.