之前有个业务需要把文件上传到ftp服务器,写了一个上传ftp的功能
package ftp
import "context"
type Client interface {
// UploadFile 上传文件
UploadFile(ctx context.Context, opt *UploadFileOpt) error
}
type UploadFileOpt struct {
Data []byte
RemoteFileName string
Dir string
}
package ftp
import (
"bytes"
"context"
"github.com/jlaffaye/ftp"
)
// FtpClient 结构体包含 FTP 客户端的配置信息
type FtpClient struct {
Addr string
Name string
Pwd string
Dir string
Connection *ftp.ServerConn
}
// NewFtpClient 创建一个新的 FtpClient 实例
func NewFtpClient(addr, name, pwd, dir string) Client {
return &FtpClient{
Addr: addr,
Name: name,
Pwd: pwd,
Dir: dir,
}
}
// Connect 连接到 FTP 服务器
func (c *FtpClient) Connect() error {
conn, err := ftp.Dial(c.Addr)
if err != nil {
return err
}
err = conn.Login(c.Name, c.Pwd)
if err != nil {
return err
}
c.Connection = conn
return nil
}
// Disconnect 断开与 FTP 服务器的连接
func (c *FtpClient) Disconnect() {
if c.Connection != nil {
c.Connection.Quit()
}
}
// UploadFile 上传文件到 FTP 服务器,接受文件内容的 []byte 数组
func (c *FtpClient) UploadFile(ctx context.Context, opt *UploadFileOpt) error {
if c.Addr == "" {
return nil
}
// 连接到 FTP 服务器
err := c.Connect()
if err != nil {
return err
}
defer c.Disconnect()
uploadDir := c.Dir
if opt.Dir != "" {
uploadDir = opt.Dir
}
// 切换到指定目录
err = c.Connection.ChangeDir(uploadDir)
if err != nil {
return err
}
// 上传文件
err = c.Connection.Stor(opt.RemoteFileName, bytes.NewReader(opt.Data))
if err != nil {
return err
}
return nil
}