package cameraFunc import ( "io" "os" "path/filepath" "github.com/gogf/gf/v2/frame/g" "github.com/jlaffaye/ftp" ) //连接到相机 FTP 服务器,下载文件 func DownLoadCameraJpgByFtp(id,deviceId string,fileType string) error { ip := "192.168.88."+deviceId+":21" // 连接到 FTP 服务器 c, err := ftp.Dial(ip) // 替换为你的 FTP 服务器地址 if err != nil { g.Dump("ftp.Dial(ip) error:",err) return err } defer c.Quit() // 登录到 FTP 服务器 err = c.Login("icatch", "icatch") // 替换为你的用户名和密码 if err != nil { g.Dump("c.Login error:",err) return err } //现在本地创建文件夹和文件 fileName := id+"_"+deviceId+"_"+fileType+".jpg" file,err := IsExistDirAndFileForCreate(id,fileName) if err != nil { defer file.Close() g.Dump("IsExistDirAndFileForCreate error:",err) return err } // 从 FTP 服务器获取文件 r,err := c.Retr("jpg/"+fileName) // 远程文件名 if err != nil { g.Dump("c.Retr error:",err) return err } defer file.Close() defer r.Close() _, err = io.Copy(file, r) if err != nil { g.Dump("io.Copy error:",err) return err } return nil } //判断当前根目录是否存在指定的文件夹和文件夹下的文件,没有则创建 func IsExistDirAndFileForCreate(id string,fileName string) (file *os.File,err error) { // 指定的目录和文件名 dirPath := "downloads_new/"+id // 目标文件夹 //fileName := "myfile.txt" // 目标文件 // 检查目录是否存在 if _, err := os.Stat(dirPath); os.IsNotExist(err) { // 目录不存在,创建目录 err := os.MkdirAll(dirPath, os.ModePerm) if err != nil { return nil,err } } // 检查文件是否存在 filePath := filepath.Join(dirPath, fileName) // 文件不存在,创建文件 file, err = os.Create(filePath) if err != nil { return nil,err } // 关闭文件 return file,nil }