如何将多个文件写入数据库,使用此代码我将多个文件上传到上传文件夹,但是如何为每个文件在数据库中创建多个行呢!
public IActionResult Create(Photos photos)
{
if (ModelState.IsValid)
{
var date = DateTime.UtcNow.AddHours(4);
var photoAddDate = photos.PhotoAddedData = date.ToString("yyyy-MM-dd','HH:mm:ss", CultureInfo.InvariantCulture);
if (photos.formFiles != null && photos.formFiles.Count > 0)
{
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
foreach (IFormFile item in photos.formFiles)
{
if (item.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(item.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
photos.PhotoPath += "/" + Path.GetFileName(item.FileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
item.CopyTo(stream);
}
}
}
_context.Add(photos);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
}
ViewData["NewsId"] = new SelectList(_context.News, "NewsId", "NewsName", photos.NewsId);
return View(photos);
}
在模型类中:
[NotMapped]
[Required]
public List<IFormFile> formFiles { get; set; }
答案 0 :(得分:0)
在您的for循环中,您需要使用以下语法
byte[] myFile = stream.ToByteArray();
var myFileClass = new myFileClass{
MyFile = myFile
};
_dbContext.MyFileTable.Add(myFileClass);