c# - 将通过 HTTP 上传到 ASP.NET 的文件上传到 C# 中的 FTP 服务器
问题描述
上传表格:
<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”。我知道问题是它试图"C:\path-to-vs-files\examplePhoto.jpg"
在 FTP 服务器上找到文件,这显然不存在。我一直在这里查看许多问题/答案,我认为我需要某种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);
}
}
推荐阅读
- scala - Scala 中 DSE Cassandra 上的 Spark SQL 查询
- ember.js - 如何减少 Windows 10 上的 ember 应用程序构建时间,但它在 ubuntu 上运行良好
- sql - Why doesn't cross join work in my query?
- javascript - 函数式编程多态性
- visual-studio - 打开 GitHub 项目时如何让 Github 以管理员身份打开 Visual Studio?
- git - 如何签出旧提交并将其推送到当前分支?
- android - 设备上的android仪器测试删除应用程序数据
- extjs - extjs 为更多列更改网格颜色单元格
- reactjs - 如何使用 Jest 和 Enzyme 在 React 中测试函数
- java - copy file from linux server directory to other directory using jsch