Negar
Negar

Reputation: 906

Multiple file upload using Request.Files["files"] MVC

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.

Upvotes: 1

Views: 9300

Answers (2)

Enoch Olaoye
Enoch Olaoye

Reputation: 154

You should use:

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

instead.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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.

Upvotes: 5

Related Questions