当用户在应用程序中上传图像时,它们会成功保存到服务器文件系统中名为“Images”的文件夹中。然而,尽管文件存储成功,但遇到图像未保存在数据库中的问题。值得注意的是,此问题与运行在 IIS 上的实时环境无关;我本地的开发环境运行没有这个问题。
public async Task<ApprovalPurchaseRequest?> ApproveRequestWithinvoice(int? id, int? decisionNumber, IFormFileCollection? image)
{
var approvalRequest = await _context.ApprovalPurchaseRequests.FindAsync(id);
var purchaseRequest = await _context.PurchaseRequests.FindAsync(approvalRequest?.RequestId);
if (_User.IsInRole("Employee Admin"))
{
string folder = "Images";
string serverFolderPath = Path.Combine(webHost.WebRootPath, folder);
if (image != null && image.Count > 0)
{
foreach (var item in image)
{
if (!Directory.Exists(serverFolderPath))
{
Directory.CreateDirectory(serverFolderPath);
}
string extension = Path.GetExtension(item.FileName);
string fileName = Guid.NewGuid().ToString() + extension;
string filePath = Path.Combine(serverFolderPath, fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await item.CopyToAsync(fileStream);
}
string relativeFilePath = "/Images/" + fileName;
Image _image = new()
{
ImagePath = relativeFilePath,
IdPurchaseRequest = purchaseRequest!.IdPurchaseRequest,
ItIsInvoise = true,
};
_context.Add(_image);
await _context.SaveChangesAsync();
}
}
}
return approvalRequest;
}