golang上传文件到ftp服务器

之前有个业务需要把文件上传到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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值