C# 多文件上传 FTP
C# Multiple files upload FTP
我有一个保存单个文件的方法。我想通过制作另一种可以同时保存多个文件的方法来以这种方式完成上传。我该怎么做
public static class FileUpload
{
public static string UploadFtp(this IFormFile file, string Location, CdnSetting cdn)
{
var fileExtension = Path.GetExtension(file.FileName);
var imageUrl = cdn.Url + Location + "/" + Guid.NewGuid().ToString() + fileExtension;
using (WebClient client = new WebClient())
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(cdn.Address + imageUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(cdn.Name, cdn.Password);
request.UsePassive = cdn.UsePassive;
request.UseBinary = cdn.UseBinary;
request.KeepAlive = cdn.KeepAlive;
byte[] buffer = new byte[1024];
var stream = file.OpenReadStream();
byte[] fileContents;
using (var ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
fileContents = ms.ToArray();
}
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
var response = (FtpWebResponse)request.GetResponse();
}
return cdn.Return + imageUrl;
}
}
您可以重复使用您的方法。循环获取文件列表。
public static IEnumerable<string> UploadFtp(this IFormFile[] files, string Location, CdnSetting cdn)
{
var result = new ConcurrentBag<string>();
Parallel.ForEach(files, f =>
{
result.Add(UploadFtp(f, Location, cdn));
});
return result;
}
如果你想一个一个上传文件而不是并行上传,foreach循环也是可以的。
我有一个保存单个文件的方法。我想通过制作另一种可以同时保存多个文件的方法来以这种方式完成上传。我该怎么做
public static class FileUpload
{
public static string UploadFtp(this IFormFile file, string Location, CdnSetting cdn)
{
var fileExtension = Path.GetExtension(file.FileName);
var imageUrl = cdn.Url + Location + "/" + Guid.NewGuid().ToString() + fileExtension;
using (WebClient client = new WebClient())
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(cdn.Address + imageUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(cdn.Name, cdn.Password);
request.UsePassive = cdn.UsePassive;
request.UseBinary = cdn.UseBinary;
request.KeepAlive = cdn.KeepAlive;
byte[] buffer = new byte[1024];
var stream = file.OpenReadStream();
byte[] fileContents;
using (var ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
fileContents = ms.ToArray();
}
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
var response = (FtpWebResponse)request.GetResponse();
}
return cdn.Return + imageUrl;
}
}
您可以重复使用您的方法。循环获取文件列表。
public static IEnumerable<string> UploadFtp(this IFormFile[] files, string Location, CdnSetting cdn)
{
var result = new ConcurrentBag<string>();
Parallel.ForEach(files, f =>
{
result.Add(UploadFtp(f, Location, cdn));
});
return result;
}
如果你想一个一个上传文件而不是并行上传,foreach循环也是可以的。