在 EF Core 中将 IFormFile 上传到 FTP
Posted
技术标签:
【中文标题】在 EF Core 中将 IFormFile 上传到 FTP【英文标题】:Upload IFormFile to FTP in EF Core 【发布时间】:2022-01-06 22:14:45 【问题描述】:我想将文件上传到本地 FTP 服务器,但文件路径错误。我认为这是由于 Handler 但我找不到错误。
文件上传;
public static class FileUpload
public static string ImageUpload(this IFormFile file, string path)
var url = @"cdnadress" + "/" + Path.GetFileName(path);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
//Load the file
FileStream stream = File.OpenRead(path);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
//Upload file
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
request = null;
return null;
创建处理程序;
public class SliderCreateHandler :
IRequestHandler<SliderCreate, ApiResponse<SliderResponse>>
private readonly IUnitOfWork _repo;
private readonly IMapper _mapper;
public SliderCreateHandler(IUnitOfWork repo, IMapper mapper)
_repo = repo;
_mapper = mapper;
public async Task<ApiResponse<SliderResponse>> Handle(
SliderCreate request, CancellationToken cancellationToken)
var mapped = _mapper.Map<Slider>(request);
var path = Environment.CurrentDirectory+ @"\Image\Slider\";
mapped.ImageUrl = request.file.ImageUpload(path);
if (string.IsNullOrEmpty(mapped.ImageUrl))
return new ErrorApiResponse<SliderResponse>(ResultMessage.UnsupportedFileType);
if (mapped == null)
return new ErrorApiResponse<SliderResponse>(ResultMessage.NotCreatedSlider);
var model = await _repo.Sliders.AddAsync(mapped);
var response = _mapper.Map<SliderResponse>(model);
return new SuccessApiResponse<SliderResponse>(response);
这是错误 ID。我在某处的这条路上赛车,或者我错过了它。你能帮帮我吗?
【问题讨论】:
【参考方案1】:如果您的目标是上传IFormFile
,那么:
IFormFile.CopyTo
来访问文件内容。都是内存中的数据。不涉及物理路径/文件。
使用IFormFile.FileName
查找文件名。一些备用名称是值得推荐的,因为浏览器可能不提供。
FtpWebRequest request =
(FtpWebRequest)FtpWebRequest.Create(@"cdnadress" + "/" + file.FileName);
// rest of your FtpWebRequest setup here
using (Stream reqStream = request.GetRequestStream())
file.CopyTo(reqStream);
【讨论】:
以上是关于在 EF Core 中将 IFormFile 上传到 FTP的主要内容,如果未能解决你的问题,请参考以下文章
如何将图像从 Asp.net Core IFormFile 上传到 Azure Blob 存储?
ASP.NET Core文件上传IFormFile于Request.Body的羁绊
ASP.NET Core文件上传IFormFile于Request.Body的羁绊
如何在.net core 中创建缩略图?使用 IFormFile 的帮助