将通过 HTTP 上传到 ASP.NET 的文件进一步上传到 C# 和 SSH.NET 中的 SFTP 服务器

Upload file uploaded via HTTP to ASP.NET further to SFTP server in C# and SSH.NET

我正在使用 SFTP 和 C# 通过 Renci SSH.NET 库设置文件传输。 我被这个问题困住了。

每当我在我的 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");
}

我期望一个文件上传到服务器的输出,但实际输出是一个正在上传到服务器的文件,其名称与我尝试上传的文件相同,但大小为 0kb,也就是空文件.

您的直接问题在这里得到解答:


虽然你不需要中间MemoryStream(而且它的效率很低)。

使用IFormFile.OpenReadStream:

using (var uplfileStream = formFile.OpenReadStream())
{
    sftp.UploadFile(uplfileStream, Name);
}