gpt4 book ai didi

c# - 如何将 IFormFile 传递到我的服务层?

转载 作者:行者123 更新时间:2023-12-05 08:08:27 26 4
gpt4 key购买 nike

我正在开发 ASP.NET Core 2 MVC 应用程序,尝试设置服务层。我有一个非常基本的应用程序,我想在其中:

  • 在姓名旁边上传一张图片
  • 向数据库添加一条记录
  • 将文件存储在磁盘上的 wwwroot 文件夹中,其命名约定与我刚刚添加的记录的主键相对应。

现在我已经在我的带有 View 模型的 Controller 中正常工作了。但我想在我的服务层中使用一个很好的方法来添加数据库和文件系统,但我没有找到将文件传递给服务的方法。

我想出了如何让数据库也添加到服务层,但没有想出如何让文件在那里做任何事情。

这是我的 Controller :

    [HttpPost]
public async Task<IActionResult> Create(CreateMentorViewModel model)
{

var mentor = new Mentor
{
FirstName = model.FirstName,
LastName = model.LastName,
Created = DateTime.Now,
};

_ctx.Add(mentor);
await _ctx.SaveChangesAsync();

int newid = mentor.Id;

if (model.Image != null)
{
var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "img/profilepics");
var fileId = newid + ".jpg";
var filePath = Path.Combine(uploads, fileId);
model.Image.CopyTo(new FileStream(filePath, FileMode.Create));
}
return RedirectToAction("Index", "Mentor");

}

我正在寻找的是关于如何将文件从 Controller 中的 View 模型发送到服务的一些指示,或者可能更重要 - 我是否应该这样做?

最佳答案

您不应在服务层中依赖 ASP.NET。改为传递 Stream:

var result = await myService.ProcessFileAsync(formFile.OpenReadStream());

关于c# - 如何将 IFormFile 传递到我的服务层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640044/

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