Home > Software design >  how to Upload a single file in the list
how to Upload a single file in the list

Time:11-04

I have a list where I upload a file for each record and send them all together to the controller. The code works correctly, but if I don't upload a file for one of them and an empty record is sent, an error occurs.

   [HttpPost]
    public async Task<IActionResult> SabtEditTaxParvanedAsync([FromForm]IEnumerable<TaxParvande> taxParvandes)
    {
        if (taxParvandes == null)
        {
            return Content("File not selected");
        }
        foreach (var item in taxParvandes)
        {
            var path = Path.Combine(_environment.WebRootPath, "ListUpload", item.prosessMastand.FileName);
            using (FileStream stream = new FileStream(path, FileMode.Create))
            {
                await item.prosessMastand.CopyToAsync(stream);
                stream.Close();
            }

           
            var taxDomainModel = new TaxDomainModel
            {
                prosessId =item.prosessId,
                prosessName = item.prosessName,
                state = item.state,                    
                FilePath = path,
            };
            _context.Add(taxDomainModel);
            await _context.SaveChangesAsync();
        }
     

        return View();
    }

CodePudding user response:

But if I don't upload a file for one of them and an empty record is sent, an error occurs.

Well, in this scenario, you might encounter null reference exception. To overcome this error you could set item.prosessMastand == null then to continue loop which will skip the error upon empty insertion.

 public async Task<IActionResult> SabtEditTaxParvanedAsync([FromForm] IEnumerable<TaxParvande> taxParvandes)
        {
            if (taxParvandes == null)
            {
                return Content("File not selected");
            }
            foreach (var item in taxParvandes)
            {
             

                if (item.prosessMastand == null)
                {
                    continue;
                }


                var path = Path.Combine(_environment.WebRootPath, "ListUpload", item.prosessMastand.FileName);
                using (FileStream stream = new FileStream(path, FileMode.Create))
                {
                    await item.prosessMastand.CopyToAsync(stream);
                    stream.Close();
                }


                var taxDomainModel = new TaxDomainModel
                {
                    prosessName = item.prosessName,
                    state = item.state,
                    filePath = path,
                };
                _context.Add(taxDomainModel);
                await _context.SaveChangesAsync();
            }


            return RedirectToAction("Index");
        }

Output: enter image description here

  • Related