Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I upload a file in MVC 6 under vNext?

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?

like image 642
Adam Szabo Avatar asked Oct 18 '14 18:10

Adam Szabo


4 Answers

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();

}
like image 119
Alexander Taran Avatar answered Nov 09 '22 03:11

Alexander Taran


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.

like image 39
AndersNS Avatar answered Nov 09 '22 02:11

AndersNS


File upload binder implemented. See commit:

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

like image 26
Boglen Avatar answered Nov 09 '22 03:11

Boglen


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);
   }
}
like image 39
Soren Avatar answered Nov 09 '22 02:11

Soren