以下是一个使用 Golang 的 net 包通过 FTP 发送文件到指定目录的示例代码:

package main

import (
    "fmt"
    "net"
    "os"
    "path/filepath"
)

func main() {
    // FTP 服务器地址和端口
    server := 'ftp.example.com:21'

    // FTP 服务器登录账号和密码
    user := 'username'
    password := 'password'

    // 本地文件路径
    localFilePath := '/path/to/local/file.txt'

    // 远程文件路径
    remoteFilePath := '/path/to/remote/file.txt'

    // 获取文件名
    filename := filepath.Base(localFilePath)

    // 打开本地文件
    file, err := os.Open(localFilePath)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()

    // 连接 FTP 服务器
    conn, err := net.Dial('tcp', server)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer conn.Close()

    // 登录 FTP 服务器
    fmt.Fprintf(conn, 'USER %s\r\n', user)
    fmt.Fprintf(conn, 'PASS %s\r\n', password)

    // 上传文件到 FTP 服务器
    fmt.Fprintf(conn, 'TYPE I\r\n')
    fmt.Fprintf(conn, 'PASV\r\n')
    fmt.Fprintf(conn, 'STOR %s\r\n', remoteFilePath)
    response := make([]byte, 1024)
    n, _ := conn.Read(response)
    fmt.Println(string(response[:n]))

    // 发送文件内容
    buffer := make([]byte, 1024)
    for {
        n, err := file.Read(buffer)
        if err != nil {
            break
        }
        conn.Write(buffer[:n])
    }

    // 关闭连接
    fmt.Fprintf(conn, 'QUIT\r\n')
    conn.Close()
}

说明:

  1. 首先定义了 FTP 服务器地址、端口、登录账号、密码、本地文件路径和远程文件路径等必要参数。

  2. 使用 os 包打开本地文件。

  3. 使用 net 包连接 FTP 服务器,并发送登录命令。

  4. 发送 FTP 命令,设置上传文件类型为二进制,打开被动模式,并上传文件到指定目录。

  5. 循环读取本地文件内容,并通过 FTP 连接发送到服务器。

  6. 最后发送 QUIT 命令关闭连接。

Golang 使用 net 包通过 FTP 上传文件到指定目录

原文地址: https://www.cveoy.top/t/topic/ozo7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录