写一个 net core 网页上上传文件到ftp
以下是一个示例代码,演示如何在 .NET Core 网页上上传文件到 FTP 服务器:
using System;
using System.IO;
using System.Net;
namespace FtpUploader
{
public class FtpUploader
{
public static void UploadFileToFTP(string ftpUrl, string ftpUsername, string ftpPassword, string localFilePath, string remoteFileName)
{
try
{
// 创建 FTP 请求对象
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpUrl + "/" + remoteFileName);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
// 读取本地文件内容
byte[] fileContent;
using (StreamReader streamReader = new StreamReader(localFilePath))
{
fileContent = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());
}
// 上传文件到 FTP 服务器
using (Stream ftpStream = ftpRequest.GetRequestStream())
{
ftpStream.Write(fileContent, 0, fileContent.Length);
}
Console.WriteLine("文件上传成功!");
}
catch (Exception ex)
{
Console.WriteLine("文件上传失败:" + ex.Message);
}
}
}
}
在你的 ASP.NET Core 控制器中,你可以调用 FtpUploader.UploadFileToFTP
方法来上传文件:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace FtpUploader.Controllers
{
public class UploadController : Controller
{
[HttpPost("upload")]
public IActionResult Upload(IFormFile file)
{
if (file != null && file.Length > 0)
{
string ftpUrl = "ftp://example.com"; // 替换为你的 FTP 服务器地址
string ftpUsername = "username"; // 替换为你的 FTP 用户名
string ftpPassword = "password"; // 替换为你的 FTP 密码
string localFilePath = Path.GetTempFileName(); // 将文件保存到临时路径
string remoteFileName = file.FileName; // 使用上传文件的原始文件名作为远程文件名
using (var stream = new FileStream(localFilePath, FileMode.Create))
{
file.CopyTo(stream);
}
FtpUploader.UploadFileToFTP(ftpUrl, ftpUsername, ftpPassword, localFilePath, remoteFileName);
// 删除本地临时文件
System.IO.File.Delete(localFilePath);
return Ok("文件上传成功!");
}
return BadRequest("没有选择文件上传。");
}
}
}
请注意,上述示例中的 ftpUrl
变量需要替换为你的实际 FTP 服务器地址,ftpUsername
和 ftpPassword
变量需要替换为你的实际 FTP 登录凭据。此外,还需要处理异常和错误情况,以便根据实际需求进行适当的处理
原文地址: http://www.cveoy.top/t/topic/iRIT 著作权归作者所有。请勿转载和采集!