" />
开发者

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开发者_Python百科" />

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.


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.


You should use:

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

instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜