Golang使用ftp上传文件
Go语言中可以使用第三方库github.com/jlaffaye/ftp
库来实现FTP文件上传。
安装:
go get -u github.com/jlaffaye/ftp
然后,使用以下代码进行文件上传:
package main
import (
"bytes"
"fmt"
"github.com/jlaffaye/ftp"
"os"
"time"
)
const (
ftpDirectoryExistsErrorCode = 550
)
func main() {
// 连接到FTP服务器,注意:不要写协议 ftp://,需要写端口 21
connection, err := ftp.Dial("ftp.example.com:21", ftp.DialWithTimeout(5*time.Second))
if err != nil {
fmt.Println(err)
return
}
// 登录
err = connection.Login("username", "password")
if err != nil {
fmt.Println(err)
return
}
// 打开要上传的文件
file, err := os.Open("local-file.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// 上传文件
destPath := "/path/on/ftp/server/remote-file.txt"
err = mkdirAll(connection, destPath)
if err != nil {
fmt.Println(err)
return
}
err = connection.Stor(destPath, file)
if err != nil {
fmt.Println(err)
return
}
// 退出
err = connection.Quit()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("File uploaded successfully.")
}
// 递归创建目录
func mkdirAll(c *ftp.ServerConn, path string) error {
paths := strings.Split(path, "/")
currentPath := ""
for _, p := range paths {
if p == "" {
continue
}
currentPath += "/" + p
if err := ftp.connection.MakeDir(currentPath); err != nil {
textProtoErr, ok := err.(*textproto.Error)
if !ok {
return err
}
if textProtoErr.Code == ftpDirectoryExistsErrorCode {
// 已经存在,不需要创建
continue
}
return err
}
}
return nil
}