在 ASP.NET MVC HttpPostedFileBase 集合中只有空项

本文关键字:集合 ASP NET MVC HttpPostedFileBase | 更新日期: 2023-09-27 18:36:43

这是我的代码:

@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 });
        }

文件上传项目始终为空。问题出在哪里?呜呜

UPD: 计算结果帖子网址: http://localhost:56193/Administration/UploadImages?_id=4&enctype=multipart%2Fform-data

在 ASP.NET MVC HttpPostedFileBase 集合中只有空项

如果需要

对文件输入进行编号以使模型绑定正常工作,则列出您的列表。在最简单的形式中,您的视图应如下所示:

<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>

和您的控制器:

    public class UploadController : Controller
    {
        //
        // GET: /Upload/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload)
        {
            return View();
        }
    }

试试下面我自己用过的帖子。为我工作。

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