Go: file upload via FTP

File Transfer Protocol (FTP) is a standard protocol used for transferring files between a client and a server over a network. In this article, well explore how to upload files via FTP in Go, a versatile and powerful programming language. Well learn how to connect to an FTP server, upload a file, and handle any errors along the way.

Lets start by installing the "goftp" library which will simplify the interaction with the FTP server. Open a terminal and type the following command to install the library:


go get github.com/jlaffaye/ftp

After installing the dependencies, lets create a new file called "main.go" and open up our favorite text editor to start coding.


package main

import (
	"fmt"
	"github.com/jlaffaye/ftp"
	"os"
)

func main() {
	// Dati di accesso al server FTP
	ftpServer := "ftp.example.com"
	username := "your_username"
	password := "your_password"

	// Percorso del file locale da caricare
	localFilePath := "path/to/your/file.txt"

	// Percorso di destinazione sul server FTP
	remoteDir := "/path/on/ftp/server/"

	// Connessione al server FTP
	ftpClient, err := ftp.Dial(ftpServer)
	if err != nil {
		fmt.Println("Errore durante la connessione al server FTP:", err)
		return
	}
	defer ftpClient.Quit()

	// Autenticazione
	err = ftpClient.Login(username, password)
	if err != nil {
		fmt.Println("Errore durante l'autenticazione:", err)
		return
	}

	// Apertura del file locale
	file, err := os.Open(localFilePath)
	if err != nil {
		fmt.Println("Impossibile aprire il file locale:", err)
		return
	}
	defer file.Close()

	// Creazione della directory remota (se non esiste)
	err = ftpClient.MakeDir(remoteDir)
	if err != nil {
		fmt.Println("Errore durante la creazione della directory remota:", err)
	}

	// Caricamento del file
	remoteFilePath := remoteDir + "file.txt"
	err = ftpClient.Stor(remoteFilePath, file)
	if err != nil {
		fmt.Println("Errore durante il caricamento del file:", err)
		return
	}

	fmt.Println("File caricato con successo!")
}


Before running the code, be sure to replace the values of "ftpServer", "username", "password", "localFilePath" and "remoteDir" with the appropriate data of your FTP server and file to upload.

Back to top