上传表格:
<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
读/写鳕鱼。但我现在还没有完全理解这个过程。
使用IFormFile.CopyTo
或IFormFile.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);
}
}