问题:在 ASP.NET Core Web API 应用程序中提交
POST
请求以上传图像以及其他表单数据时,我收到 500 内部服务器错误。如果不提供图片,请求会成功,但图片名称为空,并且不会保存图片。该应用程序旨在将上传的图像存储在网络根目录中的指定目录中。
描述:当尝试在 ASP.NET Core Web API 应用程序中通过 POST 请求上传图像和其他表单数据时,遇到 http 500 内部服务器错误。仅当请求中提供了图像时才会出现此错误;没有图片的情况下提交请求成功,但图片名称为空,并且没有保存图片。该应用程序旨在将上传的图像存储在网络根目录中的指定目录中。
[HttpPost]
public async Task<IActionResult> PostAdmin(string _userRole, int _userId, [FromForm] PostAdminDto dto)
{
var userRole = _userRole;
var userId = _userId;
if (userRole == null)
{
return NotFound("Session data not found.");
}
if (userRole != "Manager")
{
return StatusCode(StatusCodes.Status403Forbidden, "Access denied.");
}
try
{
var admin = new Admin
{
Name = dto.Name,
Phone = dto.Phone,
MgrID = userId,
Email = dto.Email,
Password = dto.Password,
Address = dto.Address,
Salary = dto.Salary,
CompID = dto.CompID,
};
if (dto.Img != null)
{
var fileName = await UploadImage(dto.Img, admin.Id);
admin.ImgName = fileName;
}
await _context.AddAsync(admin);
_context.SaveChanges();
return Ok(admin);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while processing the request: {ex}");
return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing the request.");
}
}
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<string> UploadImage(IFormFile imageFile, int adminId)
{
if (imageFile == null || imageFile.Length == 0)
{
throw new Exception("Image file is required.");
}
var fileName = $"{adminId}_{DateTime.Now.Ticks}{Path.GetExtension(imageFile.FileName)}";
var imagesDirectory = Path.Combine(_hosting.WebRootPath, "images"); // Corrected path
var filePath = Path.Combine(imagesDirectory, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(stream);
}
return fileName;
}
使用 _hosting.ContentRootPath 并确保项目中存在目录“images”