Mvc: How to Save IFormFile to SQLServer FileStream Table

Created on 7 Jul 2016  路  3Comments  路  Source: aspnet/Mvc

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:

``` c#
public class FileStorage
{
public string FileName { get; set; }
public byte[] FileStore { get; set; }
}


``` c#
[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.

question

All 3 comments

IFormFile has a CopyTo(Stream) method on it. Wouldn't the switch to it look pretty similar to what you have here?

Thanks for your quick response. I tried to use this right after you commented and at first I thought I couldn't find it because we weren't running the latest version of .net core. I installed the latest and updated my project to use the newer runtime but CopyTo does not seem to be an option for IFormFile.
code

If any of the below info helps I could really use your help in getting me pointed in the right direction.
Solution DNX SDK version: 1.0.0-rc1-update2

dnx --version
Microsoft .NET Execution environment
Version: 1.0.0-rc1-16609
Type: Clr
Architecture: x86
OS Name: Windows
OS Version: 6.3
Runtime Id: win81-x86

dnvm current Version(Default): 1.0.0-rc1-update2 clr

VS Pro 2015 Update 3

The method was introduced as part of RC2 which explain why you aren't seeing it. Updating should resolve this issue. That should you should consider switching from dnx -> dotnet. The former is no longer being supported and RC2 packages and later might no longer be compatible with dnx (See https://github.com/aspnet/Announcements/issues/176).

Was this page helpful?
0 / 5 - 0 ratings