所以要么没有人尝试过这样做,要么我只是没有找到任何东西。上传文件的旧方法是:
public class FileStorage
{
public string FileName { get; set; }
public byte[] FileStore { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(HttpPostedFileBase file)
{
FileStorage fileAttachment = new FileStorage();
using (Stream inputStream = file.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
//Check to see if stream returned is already a MemoryStream
if(memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
fileAttachment.FileStore = memoryStream.ToArray();
fileAttachment.FileName = file.FileName;
}
if (ModelState.IsValid)
{
db.FileAttachment.Add(fileAttachment);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
我知道 .Net Core 使用IFormFile
但我找到的用于保存它的所有资源都在谈论将其保存到 Web 服务器上的 wwwroot 文件夹。我已成功将文件传递给我的控制器,但无法弄清楚如何将其转换为byte[]
以保存到数据库FileStream
表。
这是我当前的代码:
[HttpPost]
public async Task<IActionResult> Upload(IFormFile uploadFile)
{
if (ModelState.IsValid)
{
var parsedContent = ContentDispositionHeaderValue.Parse(uploadFile.ContentDisposition);
var fileName = Path.Combine(_hostingEnvironment.WebRootPath, "Uploads", parsedContent.FileName.Trim('"'));
await uploadFile.SaveAsAsync(fileName);
}
return View("Index");
}
如何将其转换为与数据库一起使用FileStream