Home > Back-end >  How to create an IFormFile image file and send it to input element in view?
How to create an IFormFile image file and send it to input element in view?

Time:03-16

I have a form with an input element in my view.

<input asp-for="Image" id="mainImageInput" type="file" onchange="readURL(this,'mainImage')" accept="image/jpeg, image/png" />

I am storing all my images in a database as byte[]. How can I convert byte[] to IFormFile and send it to my view in the input element? And no, I am not asking how to display the image, I want to insert it directly into the input element as if the user has selected it using "Browse".

I tried writing this, but it doesn't work:

var ad = _context.Advertisements
            .Select(x => new {
                Id = x.Id,
                Title = x.Title,
                Description = x.Description,
                Price = x.Price,
                Location = x.Location,
                CategoryId = x.CategoryId,
                ImageInBase64 = Convert.ToBase64String(x.Image),
                UserId = x.UserId,
                ImageInByteArray=x.Image
            })
            .FirstOrDefault(x=>x.Id==id);

IFormFile file = null;
using (var stream = new MemoryStream(ad.ImageInByteArray))
{
    file = new FormFile(stream, 0, ad.ImageInByteArray.Length, "name", "fileName");
}

var viewModel = new AdvertisementViewModel()
            {
                Id = ad.Id,
                Title = ad.Title,
                Description = ad.Description,
                Price = ad.Price,
                Location = ad.Location,
                CategoryId = ad.CategoryId,
                ImageInBase64 = ad.ImageInBase64,
                UserId = ad.UserId,
                Image = file
            };
return View("Edit",viewModel);

This is the action where I should receive my image after submiting my form, all other properties are there, but I am getting null for the Image.

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize]
        public async Task<IActionResult> Edit(AdvertisementViewModel viewModel) 
        {
            // viewmodel.Image is null, so my model state will always be invalid
            // need a workaround

            if (!ModelState.IsValid)
            {
                return View(viewModel);
            }
        }

CodePudding user response:

And no, I am not asking how to display the image, I want to insert it directly into the input element as if the user has selected it using "Browse".

Due to the security reason in Broswer, I think we can't set value to <input type='file' />.

Related Posts,hope it useful to you:

1. How to set a value to a file input in HTML?

2. Set default value for a input file form [duplicate]

  • Related