gpt4 book ai didi

c# - 将通过 HTTP 上传到 ASP.NET 的文件进一步上传到 C# 中的 FTP 服务器

转载 作者:太空宇宙 更新时间:2023-11-03 22:35:25 25 4
gpt4 key购买 nike

上传表格:

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

Controller /文件上传:

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 读/写 cod。但我目前还没有完全理解这个过程。

最佳答案

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

将其与 WebClient.OpenWrite 合并:

public void Upload(IFormFile file)
{
string url = "ftp://ftp.example.com/remote/path/file.zip";
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("xxxx", "xxxx");
using (var ftpStream = client.OpenWrite(url))
{
file.CopyTo(ftpStream);
}
}
}

或者,使用 FtpWebRequest :

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

using (Stream ftpStream = request.GetRequestStream())
{
file.CopyTo(ftpStream);
}
}

关于c# - 将通过 HTTP 上传到 ASP.NET 的文件进一步上传到 C# 中的 FTP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55499008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com