asp.net-coreasp.net-core-mvc

How to upload pictures to controller


I save pictures as byte[] in the database. Im familiar with the HttpPostedFileBase in asp.net but they got rid of that in .net Core 5 apparently How can I send the uploaded picture to the controller which converts it into picture and inserts into the database?

<input name="UploadedPic" type="file"readonly />
<button type="submit">Submit</button>

C# controller

public IActionResult UploadPictures()
    {

        return null;

    }

Solution

  • At first, you have to create ViewModel for upload. and this ViewModel uses your [HttpGet] methods view.And your model should be public byte[] Image { get; set; } and your ViewModel should be public IFormFile Image { get; set; }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> UploadPictures([Bind("Image")] ProductVM productVM)
    {
        string msg = "";
        if (ModelState.IsValid)
        {
            Product p = new Product();
    
    
            //productImage
    
            string webroot = _he.WebRootPath;  // _he comes from IHostingEnvironment 
    
    
            string folder = "Product_Images";
            string imgfilename = Path.GetFileName(productVM.Image.FileName);
            string filewrite = Path.Combine(webroot, folder, imgfilename);
    
            using (MemoryStream ms = new MemoryStream())
            {
                await productVM.Image.CopyToAsync(ms);
                p.Image = ms.ToArray();
                p.ImageFile = "/" + folder + "/" + imgfilename;
            }
            using (var stream = new FileStream(filewrite, FileMode.Create))
            {
                await productVM.Image.CopyToAsync(stream);
            }
            _context.Add(p);
            await _context.SaveChangesAsync();
            msg = "Product inserted successfully!!!";
            TempData["msg"] = msg;
            return RedirectToAction(nameof(Index));
        }
        else
        {
            msg = "Product image incomplete. Please try again...";
        }
        TempData["msg"] = msg;
        return RedirectToAction("Create");
    }