如何将 IFormFile 保存到 SQLServer FileStream 表

Mr.*_*eys 5 c# filestream sqlfilestream asp.net-core-mvc

因此,要么没有人尝试这样做,要么我只是在上面找不到任何东西。您上传文件的旧方式是这样的:

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");
}
Run Code Online (Sandbox Code Playgroud)

我知道 .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");
}
Run Code Online (Sandbox Code Playgroud)

我如何将其转换为与数据库一起使用 FileStream

Kir*_*lla 6

由于似乎有很多关于如何写入 SQL Server 文件流的文章,我将避免在此处提及。

IFormFile有一个CopyToAsync你可以使用的方法。假设你掌握了 SQL Server 的文件流,所有需要做的就是

await formFile.CopyToAsync(targetSqlFileStream);