文件数据未落入控制器

本文关键字:控制器 数据 文件 | 更新日期: 2023-09-27 18:03:05

图像文件数据不属于我的控制器。我发送类型为IEnumerable<HttpPostedFileBase>的文件。

This is my View

@using (Html.BeginForm( new { @action = "/Upload",  @enctype = "multipart/form-data", @method = "POST" }))
{
    <div class="form-horizontal">
        <div class="form-group">
            <div class="col-md-10">
                @Html.Label("Pictures:", new { @class = "control-label  col-md-2" })
                @Html.TextBoxFor(model => model.files, new { @type = "file", @name = "files", @id = "files", @style = "width: 100%;", @multiple = "multiple" })
            </div>
        </div>
        <div id="divfiles"></div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
<script>
  function handleFileSelect(evt) {
      var files = evt.target.files;
      var divfiles = document.getElementById('divfiles');
      while (divfiles.hasChildNodes()) {
          divfiles.removeChild(divfiles.lastChild);
      }
    for (var i = 0, f; f = files[i]; i++) {
      if (!f.type.match('image.*')) {
        continue;
      }
      var reader = new FileReader();
      reader.onload = (function(theFile) {
        return function(e) {
            var span = document.createElement('span');
            var imgLoad = document.createElement('img');
            imgLoad.setAttribute("id", "imgLoad");
            imgLoad.setAttribute("style", "width:10%;");
            imgLoad.setAttribute("src", e.target.result);
            imgLoad.setAttribute("title", escape(theFile.name));
            span.appendChild(imgLoad);
            divfiles.insertBefore(span, null);
        };
      })(f);
      reader.readAsDataURL(f);
    }
  }
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
}

这是我的控制器

我的图片不在这里

// GET:
public ActionResult Index()
{
    var rooms = db.Rooms.Include(r => r.Hotel).Include(r => r.RoomType);
    return View(rooms.ToList());
}
// GET: Rooms/Details/
public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Room room = db.Rooms.Find(id);
    if (room == null)
    {
        return HttpNotFound();
    }
    return View(room);
}
// GET: Rooms/Create
public ActionResult Create()
{
    RoomViewModel model = new RoomViewModel();
    model.HotelIDs = from c in db.Hotels
                    select new SelectListItem
                    {
                        Text = c.Name,
                        Value = c.Id.ToString()
                    };
    model.RoomTypeIDs = from t in db.RoomTypes
                   select new SelectListItem
                   {
                       Text = t.Name,
                       Value = t.Id.ToString()
                   };
    model.EquipmentIDs = from k in db.Equipments
                      select new SelectListItem
                      {
                          Text = k.Name,
                          Value = k.Id.ToString()
                      };
    //ViewBag.HotelId = new SelectList(db.Hotels, "Id", "Name");
    //ViewBag.RoomTypeId = new SelectList(db.RoomTypes, "Id", "Name");
    //ViewBag.EquipmentsIds = new MultiSelectList(db.Equipments, "Id", "Name");
    return View(model);
}
// POST: Rooms/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files, RoomViewModel roomViewModel, int[]EquipmentIDs )
{
Room room = new Room();
    room.HotelId = roomViewModel.HotelId;
    room.RoomTypeId = roomViewModel.RoomTypeId;
    room.MaxPeople = roomViewModel.MaxPeople;
    room.WindowView = roomViewModel.WindowView;
    room.Price = roomViewModel.Price;
    room.IsDeleted = roomViewModel.IsDeleted;
    if (EquipmentIDs == null)
    {
        foreach (int EquipmentID in EquipmentIDs)
        {
            var eqp = db.Equipments.Where(t => t.Id == EquipmentID).FirstOrDefault();
            if (eqp != null)
            {
                if (room.Equipments == null)
                {
                    room.Equipments = new List<Equipment>();
                }
                room.Equipments.Add(eqp);
            }
        }
    }
    //room.RoomsPhotos = roomViewModel.files;
    if (ModelState.IsValid)
    {
        db.Rooms.Add(room);
        db.SaveChanges();
    }
    return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    return View("Index", "Hotels");
}

方法上传文件(IEnumerable files)没有出现

文件数据未落入控制器

您的代码没有生成正确的form标记。要使文件上传工作,表单的enctype属性值应该设置为"multipart/form-data"

您当前的视图代码正在呈现这样一个表单标记(检查页面的视图源)

<form action="/Upload?enctype=multipart%2Fform-data&amp;method=POST" method="post"> 
</form>  

但是为了上传工作,理想情况下它应该像

<form action="/Upload"  enctype="multipart/form-data" method="post"> 
</form> 

如果您正确使用Html.BeginForm助手方法,它将生成正确的表单标记标记,如上面所示。

应该可以

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, 
                                              new { @enctype = "multipart/form-data" }))
{
}

假设您的Upload动作方法是在HomeController。如果它是一个不同的控制器,则更新Html.BeginForm method调用的第二个参数。

如果IEnumerable<HttpPostedFileBase>不工作,试试这个:

[HttpPost]
public ActionResult Upload()
{
  var file = request.files;
}

我看过你的代码。我认为问题出在你的表单标签上。

不是

@using (Html.BeginForm( new { @action = "/Upload",  @enctype = "multipart/form-data", @method = "POST" }))

Please try this

 <form action="@Url.Action("yourActionMethod", "yourController")" method="post">
 <div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-10">
            @Html.Label("Pictures:", new { @class = "control-label  col-md-2" })
            @Html.TextBoxFor(model => model.files, new { @type = "file", @name = "files", @id = "files", @style = "width: 100%;", @multiple = "multiple" })
        </div>
    </div>
    <div id="divfiles"></div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
 
</form>

你也可以改变你的脚本,从。net核心控制器发送或接收数据的最好方法之一就是使用AJAX。https://www.w3schools.com/js/js_ajax_intro.asp这是链接。它将使编写这样的代码容易十倍。:))