错误=
SqlException:无法将值NULL插入到表“Hospitaldb.dbo. AspNetUsers”的列“PictureUrl”中;列不允许为空值。尝试失败。语句已终止。
在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;
1条答案
按热度按时间agxfikkp1#
可能问题出在视图端。你必须检查你的表单是否包含enctype ='multipart/form-data',你的输入是否包含asp-for:“Property name”,你的方法是否是post,表单是否也包含方法:“post”。如果你分享整个代码,我们可以帮助你更容易。