我注意到蛋糕支持HTTP操作,但没有FTP操作,你知道如何通过FTP创建上传文件的任务吗?
答案 0 :(得分:11)
今天在Cake中没有任何内容可以提供使用FTP协议传输文件的功能。
虽然如果您正在运行Cake" Full CLR"您可以使用FtpWebRequest
中内置的.NET框架上传文件。 FtpWebRequest
尚未移至.NET Core
,因此如果您正在运行Cake.CoreCLR
。
您可以通过使用静态ftp.cake
实用程序方法创建FTPUpload
来实现此目的,您可以从build.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");
}
#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服务器,但上面应该是一个很好的起点。
答案 1 :(得分:4)
虽然我自己没有尝试过,但我“认为”我说你可以使用Cake Addin进行文件传输操作。绝对值得与插件的原作者谈谈。
如果没有,最好的办法是为Cake创建一个自定义插件,提供您正在寻找的功能。
关于这是否应该进入Core的Cake功能集还有一个问题,但是,第一个行动方案是添加。