您可以使用 Go 标准库中的 ftp 包来发送文件。以下是一个简单的示例代码:

package main

import (
    'fmt'
    'os'
    'net'
    'net/textproto'
    'bufio'
    'path/filepath'
    'io'
)

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

    // 创建 FTP 客户端
    client := textproto.NewConn(conn)

    // 登录 FTP 服务器
    _, err = client.Cmd('USER', 'username')
    if err != nil {
        fmt.Println(err)
        return
    }
    _, err = client.Cmd('PASS', 'password')
    if err != nil {
        fmt.Println(err)
        return
    }

    // 发送文件
    localFilePath := '/path/to/local/file.txt'
    remoteFilePath := '/path/to/remote/file.txt'
    file, err := os.Open(localFilePath)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()

    _, filename := filepath.Split(localFilePath)
    response, err := client.Cmd('STOR ' + remoteFilePath + '/' + filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    if response.Code != 150 {
        fmt.Println('FTP server did not return 150')
        return
    }

    writer := bufio.NewWriter(response.Body)
    _, err = io.Copy(writer, file)
    if err != nil {
        fmt.Println(err)
        return
    }

    writer.Flush()
    response, err = client.ReadResponse(226)
    if err != nil {
        fmt.Println(err)
        return
    }
    if response.Code != 226 {
        fmt.Println('FTP server did not return 226')
        return
    }

    fmt.Println('File sent successfully')
}

请注意,此示例中的 FTP 服务器和凭据是虚构的,您需要使用您自己的 FTP 服务器和凭据。

Golang FTP 文件上传 - 使用标准库发送文件

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

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