gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 4 图像上传遇到问题

转载 作者:行者123 更新时间:2023-12-02 18:04:01 24 4
gpt4 key购买 nike

我正在尝试上传图像以及其他字段。一直在关注 here 中的示例和 here

但是图像对象似乎没有传递到 Controller ,我找不到任何错误。

这是 View :

@model Project.Models.ContentNode
@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)

<fieldset>
<legend>News</legend>

<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
@*Image upload field*@
<div class="editor-field">
<input type="file" name="file" />
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Body)
@Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

以下是 Controller 方法:

public ActionResult Create()
{
var model = new ContentNode();
return View( model );
}

[HttpPost]
public ActionResult Create(ContentNode nyF, HttpPostedFileBase imageData)
{
// Get the type of content from DB
var k = (from ct in _db.ContentTypes
where ct.ID == 1
select ct).Single();

var curUser = (from u in _db.Users
where u.Username == User.Identity.Name
select u).Single();

nyF.Author = curUser;
nyF.ContentType = k;
nyF.dateCreated = DateTime.Now;

_db.ContentNodes.Add(nyF);
_db.SaveChanges();

// Process image
if ((imageData != null && imageData.ContentLength > 0))
{
var fileName = Path.GetFileName(imageData.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
imageData.SaveAs(path);
}
else
{
return Content("The image object wasn't received");
}

return View(nyF);
}

我已经一遍又一遍地阅读整个内容,但无法看到错误。这里有人愿意指出我做错了什么吗?

最佳答案

输入文件的名称需要与操作参数匹配

<input type="file" name="file" />

应该是

<input type="file" name="imageData" />

或者您更改操作参数名称

public ActionResult Create(ContentNode nyF, HttpPostedFileBase file)

关于asp.net-mvc - ASP.NET MVC 4 图像上传遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13001710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com