在asp.net core mvc中我遇到错误,当我上传图像并单击提交按钮时出现错误

问题描述 投票:0回答:1

错误=

SqlException:无法将 NULL 值插入表“Hospitaldb.dbo.AspNetUsers”的“PictureUrl”列;列不允许为空。 INSERT 失败。该语句已终止。

在 ImageOperation.cs 文件中,

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; 
    }
}

在身份文件中,

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

在.cs文件中,

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;

我尝试过包括

string filename = Guid.NewGuid().ToString() + "_" + Path.GetFileName(file.FileName); 
反而
string filename = Guid.NewGuid().ToString() + "_" + file.FileName;

c# asp.net file-upload asp.net-core-mvc image-upload
1个回答
0
投票

问题可能出在视图方面。您必须检查您的表格是否包含 enctype='multipart/form-data', 您的输入是否包含 asp-for:"属性名称", 是你的方法 post 和表单还包含方法:“post”。如果您分享整个代码,我们可以更轻松地帮助您。

© www.soinside.com 2019 - 2024. All rights reserved.