我試圖上傳一個文件並附上一些模型信息。 在我的表格中,我已經有一個字段'圖像'(字符串)來保存圖像的相對URL。EF7 MVC ASP.NET文件上傳形式
但我真的不知道如何做上傳本身。 我已經閱讀了很多教程,但他們都使用HttpPostedFileBase,不再支持?
這是我迄今:
上傳頁面:
@using (Html.BeginForm("Lets", "Create", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<fieldset>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
@Html.LabelFor(m => m.Lets.Name, new { @class="mdl-textfield__label" })
@Html.TextBoxFor(m => m.Lets.Name, new { @class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
@Html.LabelFor(m => m.Lets.Images)
<input type="file" name="LetsImages" id="m.Lets.Images" /> <br />
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
@Html.LabelFor(m => m.Lets.Description, new { @class="mdl-textfield__label" })
@Html.TextBoxFor(m => m.Lets.Description, new { @class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
@Html.LabelFor(m => m.Lets.Credits, new { @class="mdl-textfield__label" })
@Html.TextBoxFor(m => m.Lets.Credits, new { @class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10">
@Html.LabelFor(m => m.Lets.Group)
@Html.DropDownListFor(m => m.Lets.GroupId, new SelectList(Model.Groups, "Id", "Name"), "-- Selecteer een Groep --", new { @class= "form-control" })
</div>
</div>
@Html.ActionLink("Terug naar het overzicht", "Index", new { }, new { @class= "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" })
<input type="submit" value="Save" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" />
</fieldset>
}
控制器:
[HttpGet]
public IActionResult Create()
{
var model = new LetsViewModel
{
Lets = new Lets(),
Groups = _kletsContext.Groups.AsEnumerable(),
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(LetsViewModel model)
{
LetsViewModel viewModel = null;
try
{
if(!ModelState.IsValid)
throw new Exception("The Lets model is not valid!");
var letsImage = "INSERT LOGIC FOR IMAGEUPLOAD HERE?";
model.Lets.UserId = User.GetUserId();
model.Lets.StatusId = 1;
model.Lets.Images = letsImage;
_kletsContext.Lets.Add(model.Lets);
if (_kletsContext.SaveChanges() == 0)
{
throw new Exception("The Lets model could not be saved!");
}
//Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true);
return RedirectToAction("Index", "Home");
}
catch(Exception ex)
{
ModelState.AddModelError(string.Empty, "Unable to save changes.");
viewModel = new LetsViewModel
{
Lets = model.Lets,
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
}
return View(viewModel);
}
我加,我覺得邏輯應該來的地方嗎?
所以我想要做的是:
上傳圖片到一個文件夾重命名 它 Store中的相對路徑作爲一個字符串的分貝。
謝謝