【问题标题】:Upload file uploaded via HTTP to ASP.NET further to FTP server in C#将通过 HTTP 上传到 ASP.NET 的文件上传到 C# 中的 FTP 服务器
【发布时间】:2019-04-03 15:34:53
【问题描述】:

上传表格:

<form asp-action="Upload" asp-controller="Uploads" enctype="multipart/form-data">
<input type="file" name="file" maxlength="64" />
<button type="submit">Upload</button>

控制器/文件上传:

public void Upload(IFormFile file){
    using (WebClient client = new WebClient())
    {
        client.Credentials = new NetworkCredential("xxxx", "xxxx");
        client.UploadFile("ftp://xxxx.xxxx.net.uk/web/wwwroot/images/", "STOR", file.FileName);
    }
}

问题:

出现错误“找不到文件 xxxx”。我知道问题是它试图在 FTP 服务器上找到文件,因为它是 "C:\path-to-vs-files\examplePhoto.jpg",这显然不存在。我一直在这里查看很多问题/答案,我想我需要某种FileStream 读/写代码。但我目前还没有完全理解这个过程。

【问题讨论】:

    标签: c# asp.net .net ftp webrequest


    【解决方案1】:

    使用IFormFile.CopyToIFormFile.OpenReadStream 访问上传文件的内容。

    虽然WebClient 不能与Stream interface 一起使用。所以你最好使用FtpWebRequest

    public void Upload(IFormFile file)
    {
        FtpWebRequest request =
            (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
        request.Credentials = new NetworkCredential("username", "password");
        request.Method = WebRequestMethods.Ftp.UploadFile;  
    
        using (Stream ftpStream = request.GetRequestStream())
        {
            file.CopyTo(ftpStream);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多