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?
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();
}
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.
File upload binder implemented. See commit:
https://github.com/aspnet/Mvc/commit/437eb93bdec0d9238d672711ebd7bd3097b6537d#diff-be9198f9b55d07e00edc73349c34536aR118
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);
}
}
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