0

The Error =

SqlException: Cannot insert the value NULL into column 'PictureUrl', table 'Hospitaldb.dbo.AspNetUsers'; column does not allow nulls. INSERT fails.The statement has been terminated.

In ImageOperation.cs File,

public async Task<string> ImageUpload(IFormFile file)
{
    try
    {
        if (file != null && file.Length > 0)
        {
            string fileDirectory  = Path.Combine(_env.WebRootPath, "Images");

            if (!Directory.Exists(fileDirectory ))
            {
                Directory.CreateDirectory(fileDirectory );
            }

            string filename = Guid.NewGuid().ToString() + "_" + Path.GetFileName(file.FileName);
            string filePath = Path.Combine(fileDirectory , filename);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            return filename;
        }

        return null;
    }
    catch (Exception ex)
    {
        // Log the exception
        Console.WriteLine($"Error during file upload: {ex.Message}");
        throw; 
    }
}

In Identity File,

<div class="form-floating">
    <input type="file" name="Input.PictureUrl" class="form-control" aria-required="true" />
    <span asp-validation-for="Input.PictureUrl" class="text-danger"></span>
</div>

In .cs file,

ImageOperation image = new ImageOperation(_env);
string filename = await image.ImageUpload(Input.PictureUrl);

//if (filename == null)
//{
//    // Handle the case where image upload failed, for example, return an error to the user
//    ModelState.AddModelError(string.Empty, "Image upload failed.");
//    return Page();
//}

user.PictureUrl = filename;

I tried including string filename = Guid.NewGuid().ToString() + "_" + Path.GetFileName(file.FileName); instead string filename = Guid.NewGuid().ToString() + "_" + file.FileName;

1
  • 3
    it looks like your ImageUpload returns a null - you even have a commented portion of code handling that, debug and see if it actually works. Might be your IFormFile is actually null - in that case try to add the enctype='multipart/form-data' to your form (in the view)
    – riffnl
    Commented Nov 23, 2023 at 12:41

1 Answer 1

1

Probably the problem is on view side. You must check does your form contain enctype='multipart/form-data', does your input contain asp-for:"Property name", is your method post and form also contains method:"post". If you share entire code we can help you easier.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.