1

This is my Code. I want to uplade 3 file into my database

first in View I write this : <% using (Html.BeginForm(Actionname, Controller, FormMethod.Post, new {enctype="multipart/form-data"})){%> ..... ....

and this is 3 file uplaoding:

<input type="file" name="files" id="FileUpload1" />
<input type="file" name="files" id="FileUpload2" />
<input type="file" name="files" id="FileUpload3" />

In controller I use this code:

IEnumerable<HttpPostedFileBase> files = Request.Files["files"] as IEnumerable<HttpPostedFileBase>;
foreach (var file in files)
{
byte[] binaryData = null;
HttpPostedFileBase uploadedFile = file;
if (uploadedFile != null && uploadedFile.ContentLength > 0){
 binaryData = new byte[uploadedFile.ContentLength];
 uploadedFile.InputStream.Read(binaryData, 0,uploadedFile.ContentLength);
}
}

but the files always return NULL :(

please help me, thank you.

2 Answers 2

5

Try this instead:

<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) {%>
    <input type="file" name="files" id="FileUpload1" />
    <input type="file" name="files" id="FileUpload2" />
    <input type="file" name="files" id="FileUpload3" />
    <input type="submit" value="Upload" />
<% } %>

and the corresponding controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                // TODO: do something with the uploaded file here
            }
        }
        return RedirectToAction("Index");
    }
}

It's a bit cleaner.

Sign up to request clarification or add additional context in comments.

4 Comments

Is it necessary to add "IEnumerable<HttpPostedFileBase> files" to actionResult as parameter? I do that but still NULL
Yes, this way you no longer need to use the Request.Files inside the action. The default model binder will do the job. I don't know why you are getting NULL. Are those inputs inside the form? When I tested my code I was able to fetch the uploaded files.
What if I'm already getting a model back for the rest of the things on the page as the argument to my controller method, how do I make this work then?
@JamesBender, you simply define a view model and have your controller action take this view model as parameter.
3

You should use:

IList<HttpPostedFileBase> files = Request.Files.GetMultiple("files")

instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.