简体   繁体   English

如何将 IFormFile 保存到 SQLServer FileStream 表

[英]How to Save IFormFile to SQLServer FileStream Table

So either no one has tried to do this yet or I am just not finding anything on it.因此,要么没有人尝试这样做,要么我只是在上面找不到任何东西。 The old way you would upload a file is this:您上传文件的旧方式是这样的:

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");
}

I know that the .Net Core uses IFormFile but all the resources I have found for saving it talk about saving it to the wwwroot folder on the web server.我知道 .Net Core 使用IFormFile但我找到的所有保存它的资源都谈到将它保存到 Web 服务器上的 wwwroot 文件夹。 I am successfully passing the file to my controller but have not been able to figure out how to convert it to the byte[] to save to the DB FileStream table.我已成功将文件传递给我的控制器,但无法弄清楚如何将其转换为byte[]以保存到 DB FileStream表。

Here is my current Code:这是我目前的代码:

[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");
}

How do I convert it to work with the DB FileStream如何将其转换为与 DB FileStream

Since there seem to many articles on how to write into a SQL Server's file stream, I will avoid mentioning it here.由于似乎有很多关于如何写入 SQL Server 文件流的文章,我将避免在此处提及。

IFormFile has a CopyToAsync method which you can use. IFormFile有一个可以使用的CopyToAsync方法。 Let's say you get hold of the SQL Server's file stream, all would need to do would be is假设你掌握了 SQL Server 的文件流,所有需要做的就是

await formFile.CopyToAsync(targetSqlFileStream);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM