Golang FTP File Upload: A Comprehensive Guide with Code Example
Here's an example code for sending a file via FTP in Go:
package main
import (
"fmt"
"net/url"
"os"
"path/filepath"
"github.com/jlaffaye/ftp"
)
func main() {
// FTP connection details
ftpURL := 'ftp://ftp.example.com'
ftpUsername := 'username'
ftpPassword := 'password'
// Local file path
localFilePath := '/path/to/local/file.txt'
// Remote file name
remoteFileName := 'remote_file.txt'
// Connect to FTP server
ftpURLParsed, err := url.Parse(ftpURL)
if err != nil {
fmt.Println("Error parsing FTP URL:", err)
return
}
ftpConn, err := ftp.Dial(ftpURLParsed.Host)
if err != nil {
fmt.Println("Error connecting to FTP server:", err)
return
}
defer ftpConn.Quit()
// Login to FTP server
err = ftpConn.Login(ftpUsername, ftpPassword)
if err != nil {
fmt.Println("Error logging in to FTP server:", err)
return
}
// Open local file
localFile, err := os.Open(localFilePath)
if err != nil {
fmt.Println("Error opening local file:", err)
return
}
defer localFile.Close()
// Change to FTP directory
remoteDir := ftpURLParsed.Path
if remoteDir == "" {
remoteDir = "/"
}
err = ftpConn.ChangeDir(remoteDir)
if err != nil {
fmt.Println("Error changing to FTP directory:", err)
return
}
// Upload file to FTP server
err = ftpConn.Stor(remoteFileName, localFile)
if err != nil {
fmt.Println("Error uploading file to FTP server:", err)
return
}
fmt.Println("File uploaded successfully")
}
Make sure to replace the FTP connection details, local file path, and remote file name with your own values.
原文地址: https://www.cveoy.top/t/topic/ozmI 著作权归作者所有。请勿转载和采集!