Golang FTP 文件上传:简单方法实现
以下是一个示例代码,用于发送文件到 FTP 服务器并返回错误:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
func sendFileToFtp(filepath string) error {
// 读取文件内容
content, err := ioutil.ReadFile(filepath)
if err != nil {
return fmt.Errorf('failed to read file %s: %v', filepath, err)
}
// 获取文件名
filename := filepath[strings.LastIndex(filepath, '/')+1:]
// 创建FTP请求
ftpUrl, err := url.Parse('ftp://ftp.example.com/' + filename)
if err != nil {
return fmt.Errorf('failed to parse FTP URL: %v', err)
}
ftpUrl.User = url.UserPassword('username', 'password')
req, err := http.NewRequest('PUT', ftpUrl.String(), strings.NewReader(string(content)))
if err != nil {
return fmt.Errorf('failed to create FTP request: %v', err)
}
// 发送FTP请求
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf('failed to send FTP request: %v', err)
}
defer resp.Body.Close()
// 检查FTP响应
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return fmt.Errorf('FTP request failed with status code %d', resp.StatusCode)
}
return nil
}
func main() {
// 测试发送文件
err := sendFileToFtp('/path/to/myfile.txt')
if err != nil {
fmt.Println('Error sending file to FTP:', err)
os.Exit(1)
}
fmt.Println('File sent to FTP successfully!')
}
请注意,此示例仅用于演示目的。实际使用时,您需要将FTP服务器的URL、用户名和密码替换为实际值,以及根据需要进行其他更改。
原文地址: https://www.cveoy.top/t/topic/otZE 著作权归作者所有。请勿转载和采集!