Search code examples
c#asp.netfile-uploadasp.net-core-mvcimage-upload

In asp.net core mvc I got an error, when I upload the image and click on submit button I got an error


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;


Solution

  • 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.