Attempting to upload a file using ASP.NET MVC

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

The following code works fine:

// Read in the image data.
byte[] binaryData = null;
HttpPostedFileBase uploadedFile = Request.Files["ImageFileName"];
if (uploadedFile != null &&
    uploadedFile.ContentLength > 0)
    {
        binaryData = new byte[uploadedFile.ContentLength];
        uploadedFile.InputStream.Read(binaryData, 
                                      0,
                                      uploadedFile.ContentLength);
    }

But I'm trying to use the new FileCollectionModelBinderone found in the futures assembly.

I found these two blog posts here and here explaining what to do. I follow these instructions, but havne't no luck β†’ the object filealways null.

Here is my method.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Include = "Subject, Content")]
                           Post post, 
                           HttpPostedFileBase file)
{
    UpdateModel(post);
    ...
}

Notice how I try to upload a file and load some message information into a Post object.

Can anyone make any suggestions?

For the record, I included ModelBinder in my global.asax.cs file. I also made sure the form is a message with enctype added: -

<form method="post" enctype="multipart/form-data" action="/post/create">
+5
4

: (

, .

, NAME Id/Name input type="file"!!! ( , ... ).

.

Html. ( Id/Name)

<input type="file" id="imageFileName" name="imageFileName" class="upload" />

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Include = "Subject, Content")]Post post,
    HttpPostedFileBase imageFileName)
{
...
}

shees!

+10

, :

<form enctype="multipart/form-data" ...
+5

, , HttpPostedFileBase, . , ASP.NET MVC, .

System.Web.Mvc.ValueProviderDictionary.PopulateDictionary() Request.Form, Request.QueryString RouteData, NOT Request.Files. , "" ( "", , ASP.NET MVC ).

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

/ MVC, , . . " ", / ( ), -then-upload ( "attach" ) / .

: 1) , 2)

, , Hanselman.

I can’t say that I tried the built-in complex type binding for files (HttpPostedFileBase), but I would suggest that it would be more complex than my current solution, given that reading the post, Hansel wrote above - you found out that the collection of files returned to Requestis only a typed collection.

I suggest sticking to your source code and trying to make it more secure for your purposes.

0
source

All Articles