How to Save IFormFile to SQLServer FileStream Table

Mr. Smileys picture Mr. Smileys · Jul 7, 2016 · Viewed 12.5k times · Source

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. 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.

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

Answer

Kiran Challa picture Kiran Challa · Jul 8, 2016

Since there seem to many articles on how to write into a SQL Server's file stream, I will avoid mentioning it here.

IFormFile has a CopyToAsync method which you can use. Let's say you get hold of the SQL Server's file stream, all would need to do would be is

await formFile.CopyToAsync(targetSqlFileStream);