【问题标题】:How to convert a file path to IFormFIle in ASP.NET CORE?如何在 ASP.NET CORE 中将文件路径转换为 ​​IFormFIle?
【发布时间】:2020-10-30 11:23:26
【问题描述】:

如何使用文件路径获取 IFormFile 实例?该文件在本例中是存储在 wwwroot 文件夹中的图像

我会给你一些我想要达到的目标的背景:

我想更新一个产品,所以为了做到这一点,我必须在视图上显示产品信息,包括它在<input type="file" class="form-control-file" asp-for="File"> 旁边的文件名。所以用户知道,它已经有一个图像,当然我不会因为没有选择文件而在执行 HTTP Post 请求时遇到问题(以防用户不想更新图像)。问题是产品类没有 IFormFile 属性,它只有图像名称,而视图模型负责拥有 IForm 文件。那么,在将 productViewModel 作为参数发送到 View 之前,如何将图像名称或路径转换为 ​​IFormFile?

这是我的视图、视图模型和我的产品类别:
Update.cshtml

<form enctype="multipart/form-data" method="post" asp-controller="Product" asp-action="Update">
    <div class="form-group">
        <label asp-for="Name"></label>
        <input type="text" class="form-control" asp-for="Name" placeholder="Cereal, Ice cream, Tuna, etc...">
        <span class="text-danger" asp-validation-for="Name"></span>
    </div>
    <div class="form-group">
        <label asp-for="File"></label>
        <input type="file" class="form-control-file" asp-for="File">
    </div>
    <button class="btn btn-success">Save Changes</button>
</form>

ProductViewModel.cshtml

public class ProductViewModel
{
    public string Name { get; set; }
    public IFormFile File { get; set; }
}

Product.cshtml

public class Product
{
    public string Name { get; set; }
    public string ImageName { get; set; }
}

【问题讨论】:

  • 为什么不能在视图模型中使用另一个属性ImageName?您无需在 C# 代码中设置 IFormFile。您只需要使用它来从客户端获取文件到服务器。
  • 我还建议您使用单独的属性提供已经存在现有文件的信息。摆弄文件输入非常棘手(出于安全原因),它不允许您任意设置其值,即使有办法将 IFormFile 传递回视图。

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

这是一个演示,用于更改 IFormFile 的路径:

控制器:

public IActionResult GetFile() {
            Product product = new Product { Name = "product1", ImageName = "red.PNG" };
            string path = "./wwwroot/images/" + product.ImageName;
            using (var stream = System.IO.File.OpenRead(path))
            {
                ProductViewModel productViewModel = new ProductViewModel
                {
                    Name = product.Name,

                    File = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
                };
                return Ok();
            }
            
        }

结果:

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多