我注意到 cake 支持 HTTP 操作,但没有 FTP 操作,你知道如何创建一个通过 FTP 上传文件的任务吗?
问问题
1718 次
2 回答
12
如今,Cake 中没有任何内置功能提供使用 FTP 协议传输文件的功能。
尽管如果您在“Full CLR”上运行 Cake,您可以使用内置的 .NET 框架FtpWebRequest
来上传文件。如果您正在FtpWebRequest
运行..NET Core
Cake.CoreCLR
一种方法是创建ftp.cake
一个静态FTPUpload
实用程序方法,您可以从build.cake
文件中重用该方法。
示例 ftp.cake
public static bool FTPUpload(
ICakeContext context,
string ftpUri,
string user,
string password,
FilePath filePath,
out string uploadResponseStatus
)
{
if (context==null)
{
throw new ArgumentNullException("context");
}
if (string.IsNullOrEmpty(ftpUri))
{
throw new ArgumentNullException("ftpUri");
}
if (string.IsNullOrEmpty(user))
{
throw new ArgumentNullException("user");
}
if (string.IsNullOrEmpty(password))
{
throw new ArgumentNullException("password");
}
if (filePath==null)
{
throw new ArgumentNullException("filePath");
}
if (!context.FileSystem.Exist(filePath))
{
throw new System.IO.FileNotFoundException("Source file not found.", filePath.FullPath);
}
uploadResponseStatus = null;
var ftpFullPath = string.Format(
"{0}/{1}",
ftpUri.TrimEnd('/'),
filePath.GetFilename()
);
var ftpUpload = System.Net.WebRequest.Create(ftpFullPath) as System.Net.FtpWebRequest;
if (ftpUpload == null)
{
uploadResponseStatus = "Failed to create web request";
return false;
}
ftpUpload.Credentials = new System.Net.NetworkCredential(user, password);
ftpUpload.KeepAlive = false;
ftpUpload.UseBinary = true;
ftpUpload.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
using (System.IO.Stream
sourceStream = context.FileSystem.GetFile(filePath).OpenRead(),
uploadStream = ftpUpload.GetRequestStream())
{
sourceStream.CopyTo(uploadStream);
uploadStream.Close();
}
var uploadResponse = (System.Net.FtpWebResponse)ftpUpload.GetResponse();
uploadResponseStatus = (uploadResponse.StatusDescription ?? string.Empty).Trim().ToUpper();
uploadResponse.Close();
return uploadResponseStatus.Contains("TRANSFER COMPLETE") ||
uploadResponseStatus.Contains("FILE RECEIVE OK");
}
示例用法 build.cake
#load "ftp.cake"
string ftpPath = "ftp://ftp.server.com/test";
string ftpUser = "john";
string ftpPassword = "top!secret";
FilePath sourceFile = File("./data.zip");
Information("Uploading to upload {0} to {1}...", sourceFile, ftpPath);
string uploadResponseStatus;
if (!FTPUpload(
Context,
ftpPath,
ftpUser,
ftpPassword,
sourceFile,
out uploadResponseStatus
))
{
throw new Exception(string.Format(
"Failed to upload {0} to {1} ({2})",
sourceFile,
ftpPath,
uploadResponseStatus));
}
Information("Successfully uploaded file ({0})", uploadResponseStatus);
示例输出
Uploading to upload log.cake to ftp://ftp.server.com/test...
Successfully uploaded file (226 TRANSFER COMPLETE.)
FtpWebRequest
是非常基本的,所以你可能需要调整它以适应你的目标 ftp 服务器,但上面应该是一个很好的起点。
于 2016-09-21T15:03:09.600 回答
5
虽然我自己没有尝试过,但我“认为”我说你可以使用这个Cake Addin进行文件传输操作是对的。绝对值得与插件的原作者谈谈。
如果没有,您最好为 Cake 创建一个自定义插件,以提供您正在寻找的功能。
有一个问题是,这是否也应该成为 Cake 的核心功能集,但是,第一个行动方案将是一个插件。
于 2016-09-20T15:10:20.157 回答