How to assign image file to IFormFile Variable in ASP.net Core?

How to assign image file to IFormFile Variable?

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace IFrameTesting.ViewModels
{
    public class ImageModelViewModels
    {
        [Display(Name ="Photo")]
        public IFormFile Photo { get; set; }
        public byte[] ImageData { get; set; }


        [Display(Name = "Converted Photo")]
        public IFormFile ConvertedIFormFilePhoto { get; set; }
    }
}

I have successfully converted and store to server side image. I want to get that image from server side and assign to variable ConvertedIFormFilePhoto how to acheive that?

Suppose there is image inside soultion Explore path is wwwroot/images/abc.jpg , I want to assign this abc.jpg to variable ConvertedIFormFilePhoto how to achieve it?

1 answer

  • answered 2020-05-23 06:42 Fei Han

    Suppose there is image inside soultion Explore path is wwwroot/images/abc.jpg , I want to assign this abc.jpg to variable ConvertedIFormFilePhoto how to achieve it?

    To achieve the requirement, you can try the following code snippet:

    var filepath = Path.Combine(_env.WebRootPath, @"images\" + "abc.jpg");
    
    using (var stream = System.IO.File.OpenRead($"{filepath}"))
    {
        var model = new ImageModelViewModels
        {
            ConvertedIFormFilePhoto = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
        };
    
        // ...
        // code logic here
    }