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

吃可爱长大的小学妹 提交于 2019-12-19 07:29:47

问题


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?


回答1:


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.




回答2:


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

}



回答3:


File upload binder implemented. See commit:

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




回答4:


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


来源:https://stackoverflow.com/questions/26443305/how-can-i-upload-a-file-in-mvc-6-under-vnext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!