简体   繁体   中英

in ASP.NET MVC HttpPostedFileBase collection has only null items

This is my code:

@using (Html.BeginForm("UploadImages", "Administration", new { _id = Model.Album.AlbumID, enctype = "multipart/form-data" }, FormMethod.Post))
{ 
    <input type="file" name="fileUpload" id="file1" /><br />      
    <input type="file" name="fileUpload" id="file2" /><br />      
    <input type="file" name="fileUpload" id="file3" /><br /> 
    <input name="addPhoto" type="submit" value="Добавить фото" />
}



 [Authorize]
   [HttpPost]
   public ActionResult UploadImages(int _id, IEnumerable<HttpPostedFileBase> fileUpload)
        {
            gb_albumdbEntities1 entityes = new gb_albumdbEntities1();
            foreach (var file in fileUpload)
            {
                if (file == null) continue; // **<---fileUpload items is always null!**
                string path = AppDomain.CurrentDomain.BaseDirectory + "Photos/";
                if (Path.GetFileName(file.FileName) != null)
                {
                    string filename = file.GetHashCode().ToString();
                    string fullpath = Path.Combine(path, filename);
                    file.SaveAs(fullpath);
                    entityes.Photos.AddObject(new Photo() { AlbumID = _id, PhotoUrl = @"http://site.ru/Photos/" + filename });
                }
            }
            entityes.SaveChanges();
            return RedirectToAction("AlbumEdit", new { id = _id });
        }

fileUpload items is always null. Where is the problem?Oo

UPD: calculated result post url: http://localhost:56193/Administration/UploadImages?_id=4&enctype=multipart%2Fform-data

your list if file inputs need to be numbered for model binding to work. In the simplest form your view should look something like this:

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        @using (Html.BeginForm("Index", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {            
            for (int i = 0; i < 3; i++)
            {
                @Html.TextBox(string.Format("fileUpload[{0}]", i), null, new { type="file" })<br />
            }
            <input name="submit" type="submit" value="Go" />
        }
    </div>
</body>
</html>

and your controller:

    public class UploadController : Controller
    {
        //
        // GET: /Upload/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload)
        {

            return View();
        }

    }

Try the following post which I've used myself before. Worked for me.

http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM