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