Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request.Files in ASP.NET CORE

I am trying to upload files using aspnet core using ajax request . In previous versions of .net i used to handle this using

 foreach (string fileName in Request.Files)             {                 HttpPostedFileBase file = Request.Files[fileName];                 //Save file content goes here                  fName = file.FileName;      (...) 

but now its showing error at request.files how can i get it to work ? i searched and found that httppostedfile has been changed to iformfile but how to handle request.files?

like image 587
Ironsun Avatar asked Apr 16 '16 08:04

Ironsun


People also ask

What is request files?

request.FILES is a multivalue dictionary like object that keeps the files uploaded through an upload file button.

How do I upload files to IFormFile?

Upload Single FileTo add view, right click on action method and click on add view. Then select View from left side filter and select Razor View – Empty. Then click on Add button. Create design for your view as per your requirements.

What is IFormFile C#?

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 , FileName and more. The IFormFile interface also allows us to read the contents of a file via an accessible Stream .

How do I upload multiple files to .NET core?

Uploading Multiple files in ASP.NET Core MVC To Upload multiple files, navigate to " HomeController. cs " and now in the arguments we will take multiple files using "List<IFormFile>" and we will loop through each file to save it on physical drive.


1 Answers

This is working code from a recent project. Data has been moved from Request.Files to Request.Form.Files. In case you need to convert stream to byte array - this is the only implementation that worked for me. Others would return empty array.

using System.IO; var filePath = Path.GetTempFileName(); foreach (var formFile in Request.Form.Files) {    if (formFile.Length > 0)    {       using (var inputStream = new FileStream(filePath, FileMode.Create))       {          // read file to stream          await formFile.CopyToAsync(inputStream);          // stream to byte array          byte[] array = new byte[inputStream.Length];          inputStream.Seek(0, SeekOrigin.Begin);          inputStream.Read(array, 0, array.Length);          // get file name          string fName = formFile.FileName;       }    } } 
like image 124
Kiaurutis Avatar answered Oct 04 '22 05:10

Kiaurutis