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
Save a Stream to a File using C# In the above code, CopyTo method Copies the contents of the uploaded file to the target stream. If using Asynchronous API then please use CopyToAsync method which helps in Asynchronously copying the contents of the uploaded file to the target stream without blocking the main thread.
Inside the action method, the IFormFile contents are accessible as a Stream. So for IFormFile , you need to save it locally before using the local path. After this, you can get the local file path, namely filePath .
What is IFormFile. ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to store files.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With