Why aren't file uploads binding to my viewmode

2019-06-10 07:02发布

问题:

I'm trying to bind file uploads to a ViewModel (as demonstrated in this post).

But I can't get the files to bind to the Files property on the ViewModel.

Please see the code below. What am I doing wrong?

(Edit for clarity - I'd like the uploads to bind to the VM, not have them as an Action parameter.)

ViewModel

public class PrimaryImageUploadViewModel
{
    public PrimaryImageUploadViewModel()
    {
    }

    public HttpPostedFileBase[] Files { get; set; }
    public string Title { get; set; }
}

Action

[HttpPost]
public async Task<ActionResult> Upload(PrimaryImageUploadViewModel postedModel)
{
    var requestFiles = postedModel.Files;  // THIS VALUE IS NULL - WHY?
    foreach (var f in requestFiles)
    {
        if (f.ContentLength == 0)
        {
            // do stuff
        }

    }
}

Request Headers

Accept:*/*
Content-Disposition:attachment; filename="MyImage.png"
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Origin:http://localhost:52588
Referer:http://localhost:52588/example/edit/1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload

------WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Content-Disposition: form-data; name="Title"

Some Test Title
------WebKitFormBoundaryEj8zSF9hwGU3ZQA9
Content-Disposition: form-data; name="files[]"; filename="MyImage.png"
Content-Type: image/png


------WebKitFormBoundaryEj8zSF9hwGU3ZQA9--

回答1:

 public class Model1
    {
        public HttpPostedFileBase[] Files { get; set; }
        public string Title { get; set; }
    }

Hope this helps...



回答2:

First Make sure you've set the enctype attribute on your form to multipart/form-data on your form if you want to be able to upload files:

You can access uploaded file in post action parameter,

[HttpPost]
public async Task<ActionResult> Upload(PrimaryImageUploadViewModel postedModel, HttpPostedFileBase file)
{
    if (file.ContentLength > 0)  
    {  
        string _FileName = Path.GetFileName(file.FileName);  
        string _path = Path.Combine(Server.MapPath("~/UploadedFilesFolder"), _FileName);  
        file.SaveAs(_path);  
    }            
}