Trying to upload a file with ASP.NET MVC

后端 未结 4 678
庸人自扰
庸人自扰 2021-02-10 02:44

I am trying to upload a file with ASP.NET MVC.

The following code work perfectly fine:

// Read in the image data.
byte[] binaryData = null;
HttpPostedFil         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-02-10 03:33

    Not sure if this is relevant to the question, but I've just found a way to get model binding for HttpPostedFileBase working, within complex objects. Unfortunately I had to make a change to the ASP.NET MVC source code, so it isn't for everybody.

    In System.Web.Mvc.ValueProviderDictionary.PopulateDictionary(), the value provider is being populated with the contents of Request.Form, Request.QueryString, and RouteData - but NOT Request.Files. Add the following lines to "fix" this (I say "fix" because there may be a reason the ASP.NET MVC team didn't do it in the first place).

    HttpFileCollectionBase files = ControllerContext.HttpContext.Request.Files;
    if (files != null)
    {
        string[] keys = files.AllKeys;
        foreach (string key in keys)
        {
            HttpPostedFileBase file = files[key];
            ValueProviderResult result = new ValueProviderResult(file, file.FileName, currentCulture);
            AddToDictionaryIfNotPresent(key, result);
        }
    }
    

提交回复
热议问题