System.NullReferenceException: 'Object reference not set to an instance of an object.': how can i fix this error in my code

Viewed 22

How can i fix this method for uploading images

Method for image

  [NonAction]
    public async Task<string> SaveImage(IFormFile imageFile)
    {
     //In this line is error
    string imageName = new String(Path.GetFileNameWithoutExtension(imageFile.FileName).Take(10).ToArray()).Replace(' ', '-');
    imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(imageFile.FileName);
            var imagePath = Path.Combine(_env.ContentRootPath, "Images", imageName);
            using (var fileStream = new FileStream(imagePath, FileMode.Create))
            {
                await imageFile.CopyToAsync(fileStream);
            }
            return imageName;
    }
    

Method for post

    [HttpPost]
    public async Task<ActionResult<Testt>> PostProdukt([FromForm] Testt testt)//
    {
        testt.Produkti_Foto = await SaveImage(testt.ImageFile);
        _context.Pro.Add(testt); 
        await _context.SaveChangesAsync();

        return StatusCode(201);

    }
    
    
    
0 Answers
Related