[英]How to convert a file path to IFormFIle in ASP.NET CORE?
如何使用文件路径获取 IFormFile 实例? 在这种情况下,该文件是存储在wwwroot
文件夹中的图像。
我会给你一些我想要实现的目标的背景:
我想更新一个产品,所以为了做到这一点,我必须在视图上显示产品信息,包括<input type="file" class="form-control-file" asp-for="File">
旁边的文件名<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; }
}
这是一个在操作中更改 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.