Registration

Dear SAP Community Member,
In order to fully benefit from what the SAP Community has to offer, please register at:
http://scn.sap.com
Thank you,
The SAP Community team.
Skip to end of metadata
Go to start of metadata

The SAPFTP Library - FTP Programming in ABAP

This article is dedicated to FTP Programming in ABAP. It would consist of both background and front-end transfer of files via FTP.

Applies to:

ABAP

Summary:

This article is dedicated to FTP Programming in ABAP. It would consist of both background and front-end transfer of files via FTP.

Author: Fahad Javed

Created on : 8th January 2013

Table of Contents

Intro

FTP(FileTransferProtocol) is a network protocol built on top of the TCP/IP protocol,allowing transfer of files between two host machines,over the network. FTP is used for Application-to-appication(A2A) or Business-to-business(B2B) scenarios.

SAP provides a built in client library called 'SAPFTP Library'. It has two parts:

Part A: Executable File
Executable file called SAPFTP,which is installed on the SAP Netweaver AS Abap Host,as well as installed on any client as part of the SAP Gui client installation.

Figure  :  'SAPFTP.exe' file as part of
the SAP GUI Installation

Part B: The SAPFTP library:

These are a set of RFC enabled function modules,which are provided in a Function Group named 'SFTP'. These Function Modules access the Executable via RFC to connect to an FTP host and for executing various commands. SAPFTP library implements FTP according to the RFC 959 specification. You can find more indepth information regarding RFC 959 specification using the following link: http://www.ietf.org/rfc/rfc959.txt .

List of all Function Modules in the SFTP Function Group:

The Function group SFTP, is the SAPFTP library that consists of the following function modules for FTP programming:

S.No

Function Module

Description

01

FTP_CLIENT_TO_R3

 

02

FTP_COMMAND

Execute FTP Command

03

FTP_COMMAND_LIST

 

04

FTP_CONNECT

Connect to an FTP server

05

FTP_COPY

FTP Copy

06

FTP_DISCONNECT

Disconnect from FTP server

07

FTP_R3_TO_CLIENT

 

08

FTP_R3_TO_SERVER

SAP to FTP Server Communication

09

FTP_SERVER_TO_R3

FTP Server to SAP Communication

10

FTP_START_REG_SERVER

 

11

FTP_START_SAPFTP

 

12

FTP_STOP_REG_SERVER

 

13

FTP_VERSION

Procure SAPFTP version

14

HTTP_BASE64_ENCODE

base64 encode string

15

HTTP_GET

HTTP Get

16

HTTP_GET_FILE

HTTP Get File

17

HTTP_GET_FILES

HTTP Get Files

18

HTTP_GET_FILES_255

HTTP Get Files

19

HTTP_GET_FILE_DP

HTTP Get File

20

HTTP_GET_FILE_EX

 

21

HTTP_POST

HTTP post

22

HTTP_POST_DOCUMENT

 

23

HTTP_POST_DOCUMENTS

 

24

HTTP_POST_DOCUMENT_255

 

25

HTTP_POST_FILES

HTTP Post Files

26

HTTP_POST_FILES_255

HTTP Post Files

27

HTTP_POST_FILE_EX

 

28

HTTP_PROXY_CONFIG

 

29

HTTP_PUT_COMPONENT

 

30

HTTP_PUT_FILE

 

31

HTTP_PUT_FILE_DP

 

32

HTTP_SCRAMBLE

For Encrypting Passwords

33

HTTP_VERSION

Procure SAPHTTP version

Some useful function modules that are part of the SAPFTP Library include:

(1)FTP_CONNECT
Used for connecting to an FTP host,returns a handle that is used to bind subsequent commands to the session.

Syntax:

CALL FUNCTION 'FTP_CONNECT'

*"       EXPORTING
*"             VALUE(USER) TYPE  C
*"             VALUE(PASSWORD) TYPE  C
*"             VALUE(ACCOUNT) TYPE  C OPTIONAL
*"             VALUE(HOST) TYPE  C
*"             VALUE(RFC_DESTINATION) LIKE  RFCDES-RFCDEST
*"             VALUE(GATEWAY_USER) TYPE  C OPTIONAL
*"             VALUE(GATEWAY_PASSWORD) TYPE  C OPTIONAL
*"             VALUE(GATEWAY_HOST) TYPE  C OPTIONAL
*"       IMPORTING
*"             VALUE(HANDLE) TYPE  I
*"       EXCEPTIONS
*"              NOT_CONNECTED

Example:

  CALL FUNCTION 'FTP_CONNECT'
       EXPORTING
         USER            = lv_user*"This user name is case sensitive*
         PASSWORD        = lv_password*"This password could also be scrambled via the HTTP_SCRAMBLE function module*
         HOST            = lv_host_ip*"IP Address of the host FTP Server{}.In case of Server host name,it is case sensitive*
         RFC_DESTINATION = 'SAPFTPA' or 'SAPFTP' "SAPFTPA = for background access to FTP Host server or SAPFTP = for front end access to FTP Server
       IMPORTING
         HANDLE          = HANDLE*"For performing subsequent operations for the connected FTP Session*
       EXCEPTIONS
         NOT_CONNECTED   = 1*"FTP connection failed*
         OTHERS          = 2.

(2)FTP_COMMAND
Used to execute an FTP command on the FTP host. For a complete list of supported FTP commands on an FTP host,you can execute the help command. Some of the commands includes the likes of 'PWD'(for Printing the contents of the Current Working Directory),'QUIT'(For Logging out the user currently connected to the FTP server via the 'FTP_CONNECT' function module) e.t.c.

(3)FTP_R3_TO_CLIENT
Used to transfer a file down to the front-end.

(4)FTP_CLIENT_TO_R3
Used to upload a file from the front-end.

(5)FTP_R3_TO_SERVER
Used to upload a file to the FTP host.

(6)FTP_SERVER_TO_R3
Used to download a file from the FTP host.

(7)FTP_DISCONNECT:
Used to disconnect from an FTP host.

(8)RFC_CONNECTION_CLOSE:

For Disconnecting RFC connection between SAP and FTP.
Example:
  CALL FUNCTION 'RFC_CONNECTION_CLOSE'
    EXPORTING
      destination = lc_rfc_dest"RFC Destination host.e.g:SAPFTPA
    EXCEPTIONS
      OTHERS      = 1.

For creating RFC Destinations for FTP communications:

You need to create RFC destinations for FTP communications. There is a standard report for that purpose called:
    'RSFTP005'(SAPFTP check)
instead of configuring it manually via the transaction 'SM59'(Configurations of RFC connections),it automatically creates the following two RFC destinations:
(1)SAPFTP(For invoking the RFC library on the SAP GUI frontend)
(2)SAPFTPA(For invoking the RFC library on the SAP Netweaver AS ABAP host)

Figure - A : SAP  Standard Program
(RSFTP005) for Generation of RFC
Destinations 'SAPFTP' and 'SAPFTPA'

 

Figure - B : Generated RFC Destinations
'SAPFTP' and 'SAPFTPA' as shown
in Transaction SM59

 

For testing the RFC destinations:

After setting up the RFC destinations,you can check the following report for testing them:

  'RSFTP002'(Execute FTP Command). Here you enter in the credentials(which includes fields like 'User','Password','Host','RFC Destination'). In order to test commands you enter in a command such as 'help',that displays a list of all commands that can be entered in the command field.

Figure :  Standard Program for Testing
FTP Communications (RSFTP002)

For checking the Trace of the FTP communication:

You can use the report 'RSFTP001',which displays the trace of the FTP communications,provided tracing has been enabled for BOTH RFC destinations 'SAPFTP' and 'SAPFTPA' in Transaction 'SM59'. This report not only tells you about all commands and interaction but also informs about attributes such as the working directory,SAPFTP executable file path for each of the RFC destinations mentioned above(SAPFTP and SAPFTPA). Enabling Tracing generates a trace file in the SAP GUI Working directory with the name 'dev_rfc'(For unix) and rfc.trc*(Windows 32).

Figure : Standard SAP  Program
(RSFTP001)for tracing RFC
Destinations SAPFTP & SAPFTPA

Setting Up an FTP Server:

Before you can use the SAPFTP library API's,you will first need to set up an FTP Server at least locally to test the examples that will be created in the upcoming sections. We will be using a free FTP Server called 'FileZilla Server' and an FTP client called 'FileZilla Client' for accessing the FTP Server. Both of these software packages can be downloaded from the following URL:
    http://filezilla-project.org/

Just click on the 'quick download links' area on the Main Page or download both the server and the client from the 'Download' section on the left for 'FileZilla' and 'FileZilla Server' sections respectively. See the screenshot below:

Figure : Site for Dowloading FTP
Server & FTP Client

After Downloading the FileServer executable file(in our case it is FileZilla_Server-0_9_41.exe). Double Click the installer to Kickstart the Installation procedure. Click the 'I Agree' button to Agree to the terms of the license and move forward to the next step. In the Next screen('Choose Components') ,select all options apart from the 'Source Code' option. Now Click the 'Next' button choose the Installation folder where the FTP Server will be deployed and where all FTP Interactions will take place. Now the next screen('Startup Settings') is the most important screen in the setup wizard,as here you will need to provide the 'Port Number' For which the FTP Server admin interface will listen to. in the 'Please Choose how FileZilla Server should be started:' drop down,choose either 'Install as Service,started with Windows (default)'(This will start the FTP Service each time you start up System) or choose 'Install as Service,started manually'(To Install as a Service,where you will need to start it manually by providing the Admin logon credentials).

Note(s):

> You can manually start or stop the FTP Server service by making use of the Services snap-in which can be accessed by pressing [Window + R] typing in 'services.msc' and choosing 'FileZilla Server FTP server' from the list of services by making use of the play,pause and stop buttons in the application toolbar. In case you have set the Install as a Service and set it as manual,you will need to start that service using method as mentioned above,Other wise you won't be able to connect to the FTP Server.

> Do keep in mind,that the port assigned must have privileges to be allowed for its communication. This can be set by setting the PORT number in the 'Exceptions' settings of your firewall program. Do also keep in mind that you don't assign a port number that is used for other services in Windows.

_________

Next in the 'Startup settings' select the options that will applicable to window users and click the 'install' button. after Installation,click the 'close' button.

Figure : Installation(A) - License
Agreement

Figure : Installation(B) - Choose
Components

Figure : Installation(C) - Choose
Install Location

Figure : Installation(D) - Startup
Settings(A)

Figure : Installation(E) - Startup
Settings(B)

Next you will need to start the SAP FTP Server. You can launch it by following the menu path:

                       Window menu > All Programs > File Zilla FTP Server > File Zilla Server Interface

You will be prompted with a 'Connect to Server' pop up dialog box. Provide the Server Address(IP),Port Number as set during installation and the Administrator Password(by default it is 'admin').

Figure : Installation(F) - Connecting
to the FTP Server Interface

Figure : Installation(G) - Logged in to
the FTP Server

Creating a User in the FTP Server:

You will need to create a user in the FTP Server in order to connect and perform file transfer operations in SAP. To create a user,you will need to first create a 'Group' and then create a user and assign it to that Group.

In order to create a group,go to the menu path:

               Edit > Groups

Then click the 'Add' button to add a Group,give it a name and then click the 'OK' button. Next we will create a 'User',by using the following menu path:

              Edit > Users

Then click the 'Add' button and provide the user name and user group,created in the previous step and click 'OK' and then click the 'Ok' button again to create the user. Also check the 'Password' checkbox and assign a password to the user,which will be required for accessing it via the FTP Client Software.

Figure : (A) - Creating a Group

Figure : (B) - Adding a Group

Figure : C) - Finalizing a Group

Figure : (D) - Creating a User

Figure : (E) - Adding a User to a
Group

Figure : (F) - Adding Password
to a User

Setting up a directory for a User created in the FTP Server:

After creating the user,go to the following menu path:

                               Edit > Users

Now goto the 'Shared folders' page on the left side,to set up a home directory for the user. Click on the 'Add' button and navigate to the directory that you will set as the User's Home Directory. Now select all permissions as provided in the 'Files' and 'Directories' area,by checking the respective check boxes,these will be required for certain operations such as whether a File could be created ,deleted or read from the given directory and whether directories can be listed,created or deleted e.t.c. Now click the 'Set as home dir' button to set the directory path as the default home directory of the user. Now click the 'Ok' button to complete setting up the home directory.

Figure : (G) - Adding a user
directory

Figure : (H) - Setting Permissions
and setting it as home_directory

Figure : (I) - Complete setting
up the user directory

Installing the FTP Client Software:

Before you can access the user's directory created in the FTP Server,you require an FTP client to Access to it. Installation of the FTP client software is straightforward and typical of Window Applications. Refer to the following link for the complete installation steps on the official Filezilla site:

                          https://wiki.filezilla-project.org/Client_Installation#Installing_on_Windows

Setting up the FTP Client Software to access the Directory created for the user in the FTP Server:

You can access the FTP Program,using the menu path:

                              Window > All Programs > Filezilla FTP Client > FileZilla

Figure : (A) - Executing the FTP Client
software

In order to access the FTP User's directory,you will need to create a profile to access access it. You do this by going to the menu path:

                               File > Site Manager...

                                           [OR]

                               use the keyboard shortcut of 'CTRL' + 'S'

Now click on the 'New Site' button,to create the Profile for connecting our user to the FTP Server. Give it a name(In our case it is FTP_USER).

Figure : (B) - Creating a new Profile
using the Site Manager

On the right side of site(s) tree,you will find all settings for logging into the FTP user. The 'General' tab is the most is the most used tab for setting up FTP credential settings like 'Host','Port','User','Password' e.t.c. These are the settings that were set,while setting up the FTP user and directory in the FTP Server. You can also connect to this profile using the 'Connect' button.

Figure : (C) - Setting up Login
Credentials for the Profile

Figure : (D) - Connecting to the FTP
user

Directly connecting to the User after setting it up in the Site Manager:

After setting up the profile in the Site manager,you can now quickly connect to it using the profile dropdown,which contains a list of all profile,created for different FTP Users. Just select it from the drop down and select the user to connect to it. If the ask for password option was selected,while setting up the profile,the user will be prompted to enter in the password. After successful connection,the user's home Directory is shown on the left hand side,in the 'Local Site' section. You can also check the Filezilla FTP server as well to see the log of whether the user was successfully connected or not.

Figure : (A) - Accessing the Site
manager dropdown for directly
connecting to the profile

Figure : (B) - Successfully logging
in to the FTP User

Figure : (C) - User Connection
log in the FTP Server

Sample program for connecting from an SAP Server to an FTP server[Scenario Type = FrontEnd]:

Typically you create programs that either upload data to an FTP Server from an SAP System or You read a file already uploaded to an FTP Server in an SAP System e.t.c. You typically use the following functions for Communication between an SAP system and an FTP Server:

> FTP_R3_TO_SERVER(SAP to an FTP Server)
> FTP_SERVER_TO_R3(FTP to an SAP System)

(A)Uploading a text file from an SAP system to an FTP Server with SAP Data:

Before you can proceed with the upcoming real world sample programs for FTP programming that follow,make sure that you have correctly setup the FTP Server based on the topics mentioned below:

  • Setting Up an FTP Server:
  • Creating a User in the FTP Server:
  • Setting up a directory for a User created in the FTP Server:
  • Installing the FTP Client Software:
  • Setting up the FTP Client Software to access the Directory created for the user in the FTP Server:
  • Directly connecting to the User after setting it up in the Site Manager:

When you are working with an FTP Server deployed locally on your machine,you should use the 'SAPFTP' RFC Destination,for front end communication.

The sample program that follows,will perform the following steps:

  1. User will fill in FTP user credentials in Input Parameters like 'User','Password','FTP IP Address' and 'RFC Destination'.
  2. It will scramble the password entered via the 'HTTP_SCRAMBLE' Function Module.
  3. It will then connect to the FTP server via the 'FTP_CONNECT' function module.
  4. After a successful connection it will extract the contents of the 'SFLIGHT' table in an internal table,Transfer the contents of the Internal table to be uploaded to the FTP server in the form of a text file,using the 'FTP_R3_TO_SERVER' function module.
  5. Finally,it will disconnect from the FTP Connection session,using the 'FTP_DISCONNECT' function module.

Figure : (A) - Selection Criteria
for the Frontend SAP to FTP
file upload program

Figure : (B) - SAPFTP  Frontend
in case of Local Server
[First time prompt]

Figure : (C) - FTP Communications
Log messages in the FTP
Server

Figure : (D) - Final Text file
Generated via the FTP Program

Source Code for Uploading a text file to an FTP Server based on DATA from the SAP System[FrontEnd]:

*&---------------------------------------------------------------------*
*& Report  ZFTP_FEND_A_SAP_TO_FTP
*&
*&---------------------------------------------------------------------*
*&  Developer = Fahad Javed
*&  Module = ABAP
*&  Library Used = SAPFTP
*&  Description = SAP to FTP program for uploading data from an SAP system
*&                to an FTP server in text file format
*&  Completed on = 17th April 2013
*&  Transaction Code = "ZSF_FE_A"
*&---------------------------------------------------------------------*

REPORT  zftp_fend_a_sap_to_ftp.

"FTP Communication Data Objects - [START]
SELECTION-SCREEN: BEGIN OF BLOCK a WITH FRAME TITLE text-001.
PARAMETERS:
        pa_user TYPE c LENGTH 30 LOWER CASE OBLIGATORY,"FTP Server User
        pa_pswrd TYPE c LENGTH 30 LOWER CASE OBLIGATORY ,"FTP Server User's Password
        pa_host TYPE c LENGTH 64 LOWER CASE OBLIGATORY,"IP Address of the FTP Server
        pa_rfcds LIKE rfcdes-rfcdest OBLIGATORY DEFAULT 'SAPFTP'  "RFC Destination,SAPFTP for Frontend communications(Local Connections)         .
SELECTION-SCREEN: END OF BLOCK a.

DATA:
      mi_key TYPE i VALUE 26101957,"Hardcoded Handler Key,This is always '26101957'
      mi_pwd_len TYPE i ,"For finding the length of the Password,This is used when scrambling the password
      mi_handle TYPE i."Handle for Pointing to an already connected FTP connection,used for subsequent actions on the connected FTP session

DATA:
      it_sflight TYPE STANDARD TABLE OF sflight,"Final Internal table to be uploaded as a Text file on an FTP Server
      wa_sflight LIKE LINE OF it_sflight.

Data : begin of it_final occurs 0 ,
       str(125) ,
end of it_final,
wa_final like line of it_final.

"FTP Communication Data Objects - [END]

SET EXTENDED CHECK OFF.
mi_pwd_len = STRLEN( pa_pswrd ).

CALL FUNCTION 'HTTP_SCRAMBLE'"For Encrypting the Password
  EXPORTING
    SOURCE      = pa_pswrd
    sourcelen   = mi_pwd_len
    key         = mi_key
  IMPORTING
    destination = pa_pswrd.

CALL FUNCTION 'FTP_CONNECT'"For connecting to the FTP Server's user directory
     EXPORTING
       user            = pa_user
       password        = pa_pswrd
       host            = pa_host
       rfc_destination = pa_rfcds "Using the Background SAP FTP Library as part of the SAP backend System
     IMPORTING
       handle          = mi_handle
     EXCEPTIONS
       not_connected   = 1
       OTHERS          = 2.

IF sy-subrc = 0."When FTP connection established Successfully

  SELECT carrid connid fldate planetype seatsmax seatsocc
    FROM sflight
    INTO CORRESPONDING FIELDS OF  wa_sflight.

    APPEND wa_sflight to it_sflight.

    "Final Internal table with a String
    concatenate wa_sflight-carrid wa_sflight-connid wa_sflight-fldate wa_sflight-planetype "wa_sflight-seatsmax  wa_sflight-seatsocc
    into wa_final-str SEPARATED BY '      '.
    APPEND wa_final to it_final.

  ENDSELECT.

  DATA : path(58) ."Path that points to the FTP User's Home Directory
  DATA:extension(4).
  extension = '.DAT' .

  CONCATENATE '/FTP_BACKGROUND_FILE' sy-datum extension INTO path .

  CALL FUNCTION 'FTP_R3_TO_SERVER'"For Creating a file from SAP R3 to FTP Server
    EXPORTING
      handle         = mi_handle
      fname          = path
      character_mode = 'X'
    TABLES
      text           = it_final"Final Internal table to be written to the text file in the FTP Server's Directory
    EXCEPTIONS
      tcpip_error    = 1
      command_error  = 2
      data_error     = 3
      OTHERS         = 4.

ELSE."When FTP connection Fails
  WRITE: / 'Error in FTP Command'.
ENDIF.

CALL FUNCTION 'FTP_DISCONNECT'"For Disconnecting the connected FTP Session
  EXPORTING
    handle = mi_handle
  EXCEPTIONS
    OTHERS = 1.

"For Disabling data typed in the FTP User's password field
at selection-screen output.

  loop at screen.
    if screen-name = 'PA_PSWRD'.
      screen-invisible = '1'.
      modify screen.
    endif.
  endloop.

(B)Reading a text file from an FTP Server back to an SAP System:

Once you have uploaded the text file to the FTP server,you will also need to provide a mechanism to read that text file back into SAP. This is useful for applications that create log files or data files and they need to be read back in SAP for reporting purposes. This is achieved by using a standard function module named 'FTP_SERVER_TO_R3',for reading FTP data back to SAP.

The sample program that follows,will perform the following steps:

  1. User will fill in FTP user credentials in Input Parameters like 'User','Password','FTP IP Address' and 'RFC Destination'.
  2. User will fill in the date parameter to read the log or text file uploaded via the previous program to an FTP Server.
  3. It will scramble the password entered via the 'HTTP_SCRAMBLE' Function Module.
  4. It will then connect to the FTP server via the 'FTP_CONNECT' function module.
  5. After a successful connection it will read the contents of the file uploaded to an FTP server in the form of string based internal table.The contents of the file will be read using the  'FTP_SERVER_TO_R3' function module.
  6. The contents of the file will be mapped to an internal table,so that it can be shown in an ALV report.
  7. Finally,it will disconnect from the FTP Connection session,using the 'FTP_DISCONNECT' function module.

Figure : (A) - Selection Criteria
frontend FTP to SAP file Read
Program

Figure : (B) - File to be Read
as available in the FTPServer

Figure : (C) - Final Read Report
in ALV including FTP Server Log
When the File is Read

Source Code for Reading a text file from an FTP Server into the SAP System[FrontEnd]:

*&---------------------------------------------------------------------*
*& Report  ZFTP_FEND_B_FTP_TO_SAP_READ
*&
*&---------------------------------------------------------------------*
*&  Developer = Fahad Javed
*&  Module = ABAP
*&  Library Used = SAPFTP
*&  Description = FTP to SAP program for Reading uploaded data from an FTP
*&  Server[Text File] to an SAP System in an Internal Table
*&  Completed on = 6th June 2013
*&  Transaction Code = "ZSF_FE_B_READ"
*&---------------------------------------------------------------------*

REPORT  zftp_fend_b_ftp_to_sap_read NO STANDARD PAGE HEADING.

"FTP Communication Data Objects - [START]
SELECTION-SCREEN: BEGIN OF BLOCK a WITH FRAME TITLE text-001.
PARAMETERS:
        pa_user TYPE c LENGTH 30 LOWER CASE OBLIGATORY,"FTP Server User
        pa_pswrd TYPE c LENGTH 30 LOWER CASE OBLIGATORY ,"FTP Server User's Password
        pa_host TYPE c LENGTH 64 LOWER CASE OBLIGATORY,"IP Address of the FTP Server
        pa_rfcds LIKE rfcdes-rfcdest OBLIGATORY DEFAULT 'SAPFTP', "RFC Destination,SAPFTP for Frontend communications(Local Connections)
        file_dt TYPE sy-datum OBLIGATORY DEFAULT sy-datum "The Date when the file was uploaded to FTP Server
        .
SELECTION-SCREEN: END OF BLOCK a.

DATA:
      mi_key TYPE i VALUE 26101957,"Hardcoded Handler Key,This is always '26101957'
      mi_pwd_len TYPE i ,"For finding the length of the Password,This is used when scrambling the password
      mi_handle TYPE i."Handle for Pointing to an alerady connected FTP connection,used for subsequent actions on the connected FTP session

TYPE-POOLS: slis."ALV

DATA : BEGIN OF it_final OCCURS 0 ,"Total Length of the data extracted from the Sflight fields = 47 characters
       str(125) ,
END OF it_final,
wa_final LIKE LINE OF it_final.

DATA: BEGIN OF itab_final OCCURS 0,"Internal table for Displaying data from the file in the FTP Server to an SAP System using ALV
        carrid TYPE c LENGTH 2,"carrid type sflight-carrid,
        connid TYPE c LENGTH 4,"connid type sflight-connid,
        fldate TYPE c LENGTH 10,"fldate  type sflight-fldate,
        planetype TYPE c LENGTH 10,"planetype type sflight-planetype,
      END OF itab_final,
      wa_itab_final LIKE LINE OF itab_final.

"FTP Communication Data Objects - [END]

SET EXTENDED CHECK OFF.
mi_pwd_len = STRLEN( pa_pswrd ).

CALL FUNCTION 'HTTP_SCRAMBLE'"For Encrypting the Password
  EXPORTING
    SOURCE      = pa_pswrd
    sourcelen   = mi_pwd_len
    key         = mi_key
  IMPORTING
    destination = pa_pswrd.

CALL FUNCTION 'FTP_CONNECT'"For connecting to the FTP Server's user directory
     EXPORTING
       user            = pa_user
       password        = pa_pswrd
       host            = pa_host
***         HOST            = '127.0.0.1'"IP address of the FTP Server.in case if it is configured as a text,host name is case sensitive
       rfc_destination = pa_rfcds "Using the Background SAP FTP Library as part of the SAP backend System
     IMPORTING
       handle          = mi_handle
     EXCEPTIONS
       not_connected   = 1
       OTHERS          = 2.

IF sy-subrc = 0."When FTP connection established Successfully

  DATA : path(58) ."Path that points to the FTP User's Home Directory
  DATA:extension(4).
  extension = '.DAT' .

  CONCATENATE '/FTP_BACKGROUND_FILE' file_dt extension INTO path .

  CALL FUNCTION 'FTP_SERVER_TO_R3'"For Reading a file from the FTP Server to the SAP System
    EXPORTING
      handle         = mi_handle
      fname          = path
***      BLOB_LENGTH = 125
      character_mode = 'X'"'C'
    TABLES
      text           = it_final"Final Internal table That contains the string from text file read from the FTP Server
    EXCEPTIONS
      tcpip_error    = 1
      command_error  = 2
      data_error     = 3
      OTHERS         = 4.
  IF sy-subrc = 0."If File is read Successfully
    DELETE it_final WHERE str = ''."It Returns with a Blank record at the end,so that the empty string record is deleted,
    "so that it can be properly mapped to an internal Table
    PERFORM map_data."Maps data from the FTP file to an Internal Table

    CALL FUNCTION 'FTP_DISCONNECT'"For Disconnecting the connected FTP Session
      EXPORTING
        handle = mi_handle
      EXCEPTIONS
        OTHERS = 1.

    PERFORM show_data."Shows the data extracted from the file on the FTP Server in ALV form

  ELSEIF sy-subrc <> 0."If File is not read successfully
    WRITE: / 'File Not Read from the FTP Server'.
  ENDIF.

ELSE."When FTP connection Fails
  WRITE: / 'Error in FTP Command'.
ENDIF.

"For Disabling data typed in the FTP User's password field

AT SELECTION-SCREEN OUTPUT.
  LOOP AT SCREEN.
    IF screen-name = 'PA_PSWRD'.
      screen-invisible = '1'.
      MODIFY SCREEN.
    ENDIF.
  ENDLOOP.

*&---------------------------------------------------------------------*
*& Sub-Routine  MAP_DATA
*&---------------------------------------------------------------------*
*&  Description = Maps the data from the file string to an Internal
*&                Table to be displayed as an ALV Report
*&---------------------------------------------------------------------*
FORM map_data.
  LOOP AT it_final INTO wa_final.
    wa_itab_final-carrid = wa_final-str(2).
    wa_itab_final-connid = wa_final-str+8(4).
    wa_itab_final-fldate = wa_final-str+18(8).
    wa_itab_final-planetype = wa_final-str+32(10).

    APPEND wa_itab_final TO itab_final.
  ENDLOOP.

ENDFORM.                    "MAP_DATA

*&---------------------------------------------------------------------*
*& Sub-Routine  SHOW_DATA
*&---------------------------------------------------------------------*
*&  Description = Displays the data loaded from the text file in the FTP
*&                Server to an Internal Table in ALV Form
*&---------------------------------------------------------------------*
FORM show_data.
  DATA: fieldcatalog TYPE slis_t_fieldcat_alv WITH HEADER LINE.

  fieldcatalog-fieldname   = 'CARRID'.
  fieldcatalog-seltext_l   = 'Airline Code'.
  fieldcatalog-tabname   = 'ITAB_FINAL'.
  fieldcatalog-outputlen   = 10.
  APPEND fieldcatalog TO fieldcatalog.
  CLEAR  fieldcatalog.

  fieldcatalog-fieldname   = 'CONNID'.
  fieldcatalog-seltext_l   = 'Flight Connection Number'.
  fieldcatalog-tabname   = 'ITAB_FINAL'.
  fieldcatalog-outputlen   = 10.
  APPEND fieldcatalog TO fieldcatalog.
  CLEAR  fieldcatalog.

  fieldcatalog-fieldname   = 'FLDATE'.
  fieldcatalog-seltext_l   = 'Flight date'.
  fieldcatalog-tabname   = 'ITAB_FINAL'.
  fieldcatalog-outputlen   = 10.
  APPEND fieldcatalog TO fieldcatalog.
  CLEAR  fieldcatalog.

  fieldcatalog-fieldname   = 'PLANETYPE'.
  fieldcatalog-seltext_l   = 'Aircraft Type'.
  fieldcatalog-tabname   = 'ITAB_FINAL'.
  fieldcatalog-outputlen   = 10.
  APPEND fieldcatalog TO fieldcatalog.
  CLEAR  fieldcatalog.

  DATA: is_layout TYPE  slis_layout_alv,
        gd_repid     LIKE sy-repid .

* specifying alv layout

  CLEAR is_layout.
  is_layout-colwidth_optimize = 'X'.
  is_layout-zebra = 'X'.

  gd_repid = sy-repid.

  CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
   EXPORTING

*   I_INTERFACE_CHECK                 = ' '
*   I_BYPASSING_BUFFER                = ' '
*   I_BUFFER_ACTIVE                   = ' '
   i_callback_program                = gd_repid
*   I_CALLBACK_PF_STATUS_SET          = ' '
*   I_CALLBACK_USER_COMMAND           = ' '
*   I_CALLBACK_TOP_OF_PAGE            = ' '
*   I_CALLBACK_HTML_TOP_OF_PAGE       = ' '
*   I_CALLBACK_HTML_END_OF_LIST       = ' '

  it_fieldcat             = fieldcatalog[]

*     i_structure_name                  = 'ZPRMT'

*   I_BACKGROUND_ID                   = ' '
   i_grid_title                      = 'FTP File Read Report'
*   I_GRID_SETTINGS                   =

   is_layout                         = is_layout

*   IT_FIELDCAT                       =
*   IT_EXCLUDING                      =
*   IT_SPECIAL_GROUPS                 =
*   IT_SORT                           =
*   IT_FILTER                         =
*   IS_SEL_HIDE                       =
   i_default                         = 'X'

   i_save                            = 'A'

*   IS_VARIANT                        =
*   IT_EVENTS                         =
*   IT_EVENT_EXIT                     =
*   IS_PRINT                          =
*   IS_REPREP_ID                      =
*   I_SCREEN_START_COLUMN             = 0
*   I_SCREEN_START_LINE               = 0
*   I_SCREEN_END_COLUMN               = 0
*   I_SCREEN_END_LINE                 = 0
*   I_HTML_HEIGHT_TOP                 = 0
*   I_HTML_HEIGHT_END                 = 0
*   IT_ALV_GRAPHICS                   =
*   IT_HYPERLINK                      =
*   IT_ADD_FIELDCAT                   =
*   IT_EXCEPT_QINFO                   =
*   IR_SALV_FULLSCREEN_ADAPTER        =
* IMPORTING
*   E_EXIT_CAUSED_BY_CALLER           =
*   ES_EXIT_CAUSED_BY_USER            =

    TABLES
      t_outtab                          = itab_final
   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.                    "SHOW_DATA

(C)Deleting a  file from  an FTP Server:

You can also delete files uploaded to an FTP Server. To achieve this,you can make use of the 'FTP_COMMAND' function module for seeking out the list of files in the current FTP directory and also for deleting the specific file in the Directory. Here you will need to make use of the 'FTP_COMMAND' function with a command of 'delete',which is used for deleting files from the current working directory of the FTP Server. You will need to concatenate the name of the file with the delete command separated by a space and pass it to the command parameter.

Note(s):

> If there is no write access to the FTP Home directory,than you might get errors with regards to deleting a file,so do maksure that write access is enabled. see the section on setting up the FTP Server for more details.

_______

The sample program that follows,will perform the following steps:

  1. User will fill in FTP user credentials in Input Parameters like 'User','Password','FTP IP Address' and 'RFC Destination'.
  2. User will fill in the date parameter to delete the file based on the naming convention when these files were created on the FTP Server.
  3. It will scramble the password entered via the 'HTTP_SCRAMBLE' Function Module.
  4. It will then connect to the FTP server via the 'FTP_CONNECT' function module.
  5. After a successful connection it will concatenate the delete command with the file name and pass it to the function module named 'FTP_COMMAND' for deleting the file off the FTP Server. This deletion of file will be carried out if the Delete File checkbox is checked.
  6. A list report like log will be generated after the command has been executed whether it was successful or not.
  7. Finally,it will disconnect from the FTP Connection session,using the 'FTP_DISCONNECT' function module.

Figure : (A) - File to be Deleted
on FTP Server

Figure : (B) - Selection Criteria
of the FTP file deletion program

Figure : (C) - Log after Successful
File Deletion

Figure : (D) - File Deleted from
the Home Directory of FTP
Server 

Source Code for Deleting a text file from an FTP Server via the FTP_COMMAND Function Module[FrontEnd]:

*&---------------------------------------------------------------------*
*& Report  ZFTP_FEND_C_FTP_TO_SAP_DELETE
*&
*&---------------------------------------------------------------------*
*&  Developer = Fahad Javed
*&  Module = ABAP
*&  Library Used = SAPFTP
*&  Description = FTP to SAP program for Deleting a file from an FTP Server
*&                based on date selection of the generated file
*&  Completed on = 19th June 2013
*&  Transaction Code = "ZSF_FE_C_DELETE"
*&---------------------------------------------------------------------*

REPORT  zftp_fend_c_ftp_to_sap_delete NO STANDARD PAGE HEADING.

"FTP Communication Data Objects - [START]
SELECTION-SCREEN: BEGIN OF BLOCK a WITH FRAME TITLE text-001.
PARAMETERS:
        pa_user TYPE c LENGTH 30 LOWER CASE OBLIGATORY,"FTP Server User
        pa_pswrd TYPE c LENGTH 30 LOWER CASE OBLIGATORY ,"FTP Server User's Password
        pa_host TYPE c LENGTH 64 LOWER CASE OBLIGATORY,"IP Address of the FTP Server
        pa_rfcds LIKE rfcdes-rfcdest OBLIGATORY DEFAULT 'SAPFTP', "RFC Destination,SAPFTP for Frontend communications(Local Connections)
        file_dt TYPE sy-datum OBLIGATORY DEFAULT sy-datum, "The Date when the file was uploaded to FTP Server
        file_del type c as CHECKBOX
        .
SELECTION-SCREEN: END OF BLOCK a.

DATA:
      mi_key TYPE i VALUE 26101957,"Hardcoded Handler Key,This is always '26101957'
      mi_pwd_len TYPE i ,"For finding the length of the Password,This is used when scrambling the password
      mi_handle TYPE i."Handle for Pointing to an alerady connected FTP connection,used for subsequent actions on the connected FTP session

"FTP Communication Data Objects - [END]

"File Deletion Data Objects - [START]
data: begin of result occurs 0,
      line(100) type c,
      end of result.

data:
      compress type c VALUE 'N',
      fl_del_cm type c length 80."File deletion command along with the file path to file
"File Deletion Data Objects - [END]

SET EXTENDED CHECK OFF.
mi_pwd_len = STRLEN( pa_pswrd ).

CALL FUNCTION 'HTTP_SCRAMBLE'"For Encrypting the Password
  EXPORTING
    SOURCE      = pa_pswrd
    sourcelen   = mi_pwd_len
    key         = mi_key
  IMPORTING
    destination = pa_pswrd.

CALL FUNCTION 'FTP_CONNECT'"For connecting to the FTP Server's user directory
     EXPORTING
       user            = pa_user
       password        = pa_pswrd
       host            = pa_host
***         HOST            = '127.0.0.1'"IP address of the FTP Server.in case if it is configured as a text,host name is case sensitive
       rfc_destination = pa_rfcds "Using the Background SAP FTP Library as part of the SAP backend System
     IMPORTING
       handle          = mi_handle
     EXCEPTIONS
       not_connected   = 1
       OTHERS          = 2.

IF sy-subrc = 0."When FTP connection established Successfully

  DATA : path(58) ."Path that points to the FTP User's Home Directory
  DATA:extension(4)."Extension of the file
  extension = '.DAT' .

  CONCATENATE '/FTP_BACKGROUND_FILE' file_dt extension INTO path .

  PERFORM FTP_FILE_DELETE."Deletes the selected file from the FTP Server

    CALL FUNCTION 'FTP_DISCONNECT'"For Disconnecting the connected FTP Session
      EXPORTING
        handle = mi_handle
      EXCEPTIONS
        OTHERS = 1.

call function 'RFC_CONNECTION_CLOSE'
  exporting
    destination = pa_rfcds
  exceptions
    others = 1.

ELSE."When FTP connection Fails
  WRITE: / 'Error in FTP Command'.
ENDIF.

*&---------------------------------------------------------------------*
*& Sub-Routine  FTP_FILE_DELETE
*&---------------------------------------------------------------------*
*&  Description = Deletes the File residing on the FTP Server
*&                with the selected file based on the date parameter
*&---------------------------------------------------------------------*
FORM FTP_FILE_DELETE.
    if file_del = 'X'."Delete file,when checked
    CONCATENATE 'delete' path into fl_del_cm SEPARATED BY space."Deletion Command + file Path

      CALL FUNCTION 'FTP_COMMAND'
        EXPORTING
         HANDLE                = mi_handle
          command               = fl_del_cm
         COMPRESS              = compress
*         VERIFY                =
*       IMPORTING
*         FILESIZE              =
*         FILEDATE              =
*         FILETIME              =
        tables
          data                  = result
       EXCEPTIONS
         TCPIP_ERROR           = 1
         COMMAND_ERROR         = 2
         DATA_ERROR            = 3
         OTHERS                = 4
                .

"For writing in the commands executed during FTP Operation - [START]
        loop at result.
          write at / result-line.
        endloop.

  refresh result.
"For writing in the commands executed during FTP Operation - [END]

      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."don't delete file when unchecked

  endif."File Deletion Parameter check
ENDFORM.

"For Disabling data typed in the FTP User's password field

AT SELECTION-SCREEN OUTPUT.
  LOOP AT SCREEN.
    IF screen-name = 'PA_PSWRD'.
      screen-invisible = '1'.
      MODIFY SCREEN.
    ENDIF.
  ENDLOOP.

 

Useful Information

This article is dedicated to FTP Programming in ABAP. It would consist of both background and front-end transfer of files via FTP.

6 Comments

  1. Former Member

    Hello Fahad Javed,

    Thanks! I was looking for this functionality for our implementation, it was indeed very helpful

    Regards,

    Prasad

  2. Dear Prasad,

    Thanks a lot for the appreciation. Do stay tuned to this wiki,as i will be updating it with more FTP functionality,as soon as i get some time.

    Regards,

    Fahad

  3. Former Member

    Hi! I have quite the same setup, but UTF-8 commands don't work. Can you check if you can create and navigate through folders with chinese symbols? Looks like the command to enable UTF-8 from SAP to Filezilla doesn't reach filezilla as it is returned as 'invalild command' from the RFC-Destination. :/

  4. Nice job. It really helped me a lot.

  5. Former Member

    Thanks for the wonderful documentation.

  6. Nice job. It's really worth posting it in your blog. The wiki is more useful for being enriched by the community.