简体   繁体   中英

How to convert a file path to IFormFIle in ASP.NET CORE?

How do i get an IFormFile Instance using a file path?. The file, in this case is an Image stored in the wwwroot folder.

I'll give you a little bit of context of what i am trying to achieve:

I want to update a product so in order to do that i have to display the product information on the view, including it's file name next to the <input type="file" class="form-control-file" asp-for="File"> . So the user knows,it has already an image, and of course i won't have problem doing the HTTP Post Request because no file was selected (In case the user doesn't want to update the image). The problem is that product class doesn't have an IFormFile property, it only has it's image name, and the view model is responsible of having the IForm File. So again how do i convert the image name or path into a IFormFile before sending the productViewModel as a parameter to the View?

Here's my view,view model and my product class:
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; }
}

Here is a demo to change path to IFormFile in Action:

Controller:

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();
            }
            
        }

Result: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM