7

In MVC 5 I used to do this:

var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
var file = (HttpPostedFileBase)context.Request.Files[0];

Now these are not available in MVC 6 under vNext. How can I get the file(s) from the request?

Søren
  • 6,517
  • 6
  • 43
  • 47
Adam Szabo
  • 11,302
  • 18
  • 64
  • 100
  • Related post - [MVC 6 HttpPostedFileBase?](https://stackoverflow.com/q/29836342/465053) – RBT Sep 21 '21 at 11:30

4 Answers4

8

Answer below is about beta6 version.

It is now in the framework. With some caveats so far, to get the uploaded file name you have to parse headers. And you have to inject IHostingEnvironment in your controller to get to wwwroot folder location, because there is no more Server.MapPath()

Take this as example:

public class SomeController : Controller
{

    private readonly IHostingEnvironment _environment;

    public SomeController(IHostingEnvironment environment)
    {       
        _environment = environment;
    }

    [HttpPost]
    public ActionResult UploadFile(IFormFile file)//, int Id, string Title)
    {

        if (file.Length > 0)
        {
            var targetDirectory = Path.Combine(_environment.WebRootPath, string.Format("Content\\Uploaded\\"));
            var fileName = GetFileName(file);
            var savePath = Path.Combine(targetDirectory, fileName);

            file.SaveAs(savePath);
            return Json(new { Status = "Ok" });
        }
        return Json(new { Status = "Error" });
    }

    private static string GetFileName(IFormFile file) => file.ContentDisposition.Split(';')
                                                                .Select(x => x.Trim())
                                                                .Where(x => x.StartsWith("filename="))
                                                                .Select(x => x.Substring(9).Trim('"'))
                                                                .First();

}
Alexander Taran
  • 6,655
  • 2
  • 39
  • 60
  • 3
    I can't get this to work - IFormFile is always null. Always get this log: " Executing action method with arguments () - ModelSate is Valid'" – RichardM Nov 30 '15 at 22:47
  • 3
    It will not work unless you set enctype="multipart/form-data" on form tag! – EvAlex Jan 06 '16 at 19:35
  • 2
    Thanks @EvAlex, that set me on the right track. The magic with Postman and vNext is that the Key name for your file exactly match the IFormFile argument name in your POST method. – RichardM Feb 08 '16 at 17:07
  • It works well, but my requirement is to also receive one or more text values (``) with the file. Suppose I've an update profile page which includes one profile pic and three-four regular text field. How would you parse such request on the server side? I am really facing this issue since long and not able to find solution until now. http://stackoverflow.com/q/40629947/1306394 – shashwat Nov 17 '16 at 03:01
  • What if you post with [HttpPost] public JsonResult Upload(), for example with blueimp jquery upload? – JoshYates1980 Jan 29 '17 at 00:12
6

FileUpload isn't implemented in MVC6 yet, see this issue, and related issues such as this one for status.

You can post an XMLHttpRequest from JavaScript and catch it with something like this code:

public async Task<IActionResult> UploadFile()
{
    Stream bodyStream = Context.Request.Body;

    using(FileStream fileStream = File.Create(string.Format(@"C:\{0}", fileName)))
    {

        await bodyStream.CopyToAsync(fileStream);

    }

  return new HttpStatusCodeResult(200);
}

Edit: If you see the issues linked, they have now been closed. You can use a more normal way to upload files in MVC6 now.

AndersNS
  • 1,597
  • 16
  • 24
  • Thanks! Worth mentioning that because this grabs the request body as it is, it only works with non-chunked file uploaders (e.g. Valums), but doesn't work with newer ones which upload in chunked format (e.g. Flow) – Adam Szabo Oct 19 '14 at 11:00
6

File upload binder implemented. See commit:

https://github.com/aspnet/Mvc/commit/437eb93bdec0d9238d672711ebd7bd3097b6537d#diff-be9198f9b55d07e00edc73349c34536aR118

Boglen
  • 61
  • 1
  • 1
3

The easiest way to upload a file in ASP.NET Core 1.0 (MVC 6)
view (cshtml) :

<form method="post" asp-action="Upload" asp-controller="Home" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="upload"/>
</form>

controller (cs) :

[HttpPost]
public IActionResult Upload(IFormFile file)
{
    if (file == null || file.Length == 0)
        throw new Exception("file should not be null");

    // RC1
    // var originalFileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');    
    // file.SaveAs("your_file_full_address");

   // RC2
   using (var fileStream = new FileStream("path_address", FileMode.Create))
   {
       await file.CopyTo(fileStream);
   }
}
Søren
  • 6,517
  • 6
  • 43
  • 47