[英]Upload file uploaded via HTTP to ASP.NET further to SFTP server in C# and SSH.NET
I'm setting up a file transfer through Renci SSH.NET library using SFTP and C#.我正在使用 SFTP 和 C# 通过 Renci SSH.NET 库设置文件传输。 And I'm stuck on this problem.
我被困在这个问题上。
Whenever I upload a file in my ASP .NET Core program it sends the file, but it sends it as an empty file with the same name.每当我在 ASP .NET Core 程序中上传文件时,它都会发送该文件,但会将其作为同名的空文件发送。
public async Task<IActionResult> UploadFiles(List<IFormFile> files)
{
string host = "----";
string username = "----";
string password = "----";
string Name = "";
var Stream = new MemoryStream();
List<MemoryStream> stream = new List<MemoryStream>();
var connectionInfo = new Renci.SshNet.ConnectionInfo(host, username, new PasswordAuthenticationMethod(username, password));
var sftp = new SftpClient(connectionInfo);
sftp.Connect();
sftp.ChangeDirectory("DIRECTORY");
try
{
//Read the FileName and convert it to Byte array.
foreach (var formFile in files)
{
var memoryStream = new MemoryStream();
await formFile.CopyToAsync(memoryStream);
Name = formFile.FileName;
using (var uplfileStream = memoryStream)
{
sftp.UploadFile(uplfileStream, Name, null);
}
}
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
sftp.Disconnect();
return View("Inbox");
}
I expect an output where a file is uploaded to the server, but the actual output is a file being uploaded to the server with the same name as the file I tried to upload, but the size is 0kb aka its empty.我希望输出文件上传到服务器,但实际输出是上传到服务器的文件与我尝试上传的文件同名,但大小为 0kb,也就是空的。
Your immediate problem is answered here:您当前的问题在这里得到解答:
Upload from ByteArray/MemoryStream using SSH.NET - File gets created with size 0KB使用 SSH.NET 从 ByteArray/MemoryStream 上传 - 创建的文件大小为 0KB
Though you do not need the intermediate MemoryStream
(and it's inefficient anyway).尽管您不需要中间的
MemoryStream
(而且它的效率很低)。
Use IFormFile.OpenReadStream
:使用
IFormFile.OpenReadStream
:
using (var uplfileStream = formFile.OpenReadStream())
{
sftp.UploadFile(uplfileStream, Name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.