matinal:ABAP链接FTP把txt文件数据获取到内表

2023-10-14 14:00:11 浏览数 (1)

啥都不说,直接上代码

代码语言:javascript复制
*******  如果无法链接FTP,可能需要往表SAPFTP_SERVERS加入IP地址和端口(21)即可

DATA:p_host   TYPE char64  VALUE 'IP', "IP
     p_uname  TYPE char30  VALUE 'username' ,    "用户名称
     p_pwd    TYPE char30  VALUE 'password' .   "用户密码

DATA:dest     LIKE rfcdes-rfcdest VALUE 'SAPFTP',
     compress TYPE c  VALUE 'N'.

DATA:hdl     TYPE i,
     key     TYPE i VALUE 26101957,
     slen    TYPE i,
     cmd(80) TYPE c VALUE  'cd /文件夹/',     "ftp的操作  具体可以百度
     blen TYPE i.

DATA:lv_file(40).   "存放文件名

DATA:BEGIN OF result OCCURS 0,
       line(100) TYPE c,
     END OF result.

DATA:BEGIN OF ls_line,
        line(2000),
     END OF ls_line,
     lt_line LIKE TABLE OF ls_line.

DATA:i_bintab TYPE w3mimetabtype .

  slen = strlen( p_pwd ).

* "获取加密密码 保存到P_PWD
  CALL FUNCTION 'HTTP_SCRAMBLE'
    EXPORTING
      source      = p_pwd
      sourcelen   = slen
      key         = key
    IMPORTING
      destination = p_pwd.

* 连接ftp服务器
  CALL FUNCTION 'FTP_CONNECT'
    EXPORTING
      user            = p_uname
      password        = p_pwd
      host            = p_host
      rfc_destination = dest
    IMPORTING
      handle          = hdl.  "连接的句柄

   CALL FUNCTION 'FTP_COMMAND'
     EXPORTING
       handle        = hdl
       command       = cmd         "进入指定ftp目录
       compress      = compress
     TABLES
       data          = result
     EXCEPTIONS
       command_error = 1
       tcpip_error   = 2.
*******   LOOP AT result.
*******     WRITE AT / result-line.
*******   ENDLOOP.

  lv_file = '*******.txt'.    "ftp目录下的文件名(只支持*.txt OR *.dat)
*  解析*.txt 文件
  "1.在代码中由于有中文,所以需先得到BIN的内表
  "2.使用SCMS_BINARY_TO_TEXT把BIN的二进制值转换为GB2312
  CALL FUNCTION 'FTP_SERVER_TO_R3'
    EXPORTING
      handle         = hdl
      fname          = lv_file
*      character_mode = 'X'
    IMPORTING
      blob_length    = blen
    TABLES
      blob           = i_bintab
*      text           = lt_line
    EXCEPTIONS
      tcpip_error    = 1
      command_error  = 2
      data_error     = 3
      OTHERS         = 4.
  "转换BIN内表数据
  CALL FUNCTION 'SCMS_BINARY_TO_TEXT'
    EXPORTING
      input_length  = blen
      encoding      = '8400' "4110:UTF8,8400:GB2312
    IMPORTING
      output_length = blen
    TABLES
      binary_tab    = i_bintab
      text_tab      = lt_line
    EXCEPTIONS
      failed        = 1
      OTHERS        = 2.

  CALL FUNCTION 'FTP_DISCONNECT'
    EXPORTING
      handle = hdl.

  CALL FUNCTION 'RFC_CONNECTION_CLOSE'
    EXPORTING
      destination = dest
    EXCEPTIONS
      OTHERS = 1.

0 人点赞