問題描述
上傳表格:
<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-filesexamplePhoto.jpg"
,這顯然不存在.我一直在這里查看許多問題/答案,我認為我需要某種 FileStream
讀/寫代碼.但我目前還沒有完全理解這個過程.
Getting error "Could not find file xxxx". I understand the issue is that it's trying to find the file as it is "C:path-to-vs-filesexamplePhoto.jpg"
on the FTP server, which obviously doesn't exist. I've been looking at many questions/answers on here and I think I need some kind of FileStream
read/write cod. But I'm not fully understanding the process at the moment.
推薦答案
使用 IFormFile.CopyTo
或 IFormFile.OpenReadStream
來訪問上傳文件的內容.
Use IFormFile.CopyTo
or IFormFile.OpenReadStream
to access the contents of the uploaded file.
雖然 WebClient
無法使用 Stream
接口.所以你最好使用 FtpWebRequest
一個>:
Though WebClient
cannot work with Stream
interface. So you better use 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);
}
}
這篇關于將通過 HTTP 上傳到 ASP.NET 的文件上傳到 C# 中的 FTP 服務器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!