我有一个 ASP.NET MVC 网站。我需要一个页面,用户必须在其中输入多个字段,包括图像文件。
我可以找到很多很多使用 MVC 上传文件的参考资料。但他们不会将文件作为包含其他字段的表单的一部分上传。
理想情况下,字段和文件将发送到单个控制器。有小费吗?
如果您不使用第三方库,请尝试以下操作:
Model
public class Strategy
{
public int ID { get; set; }
public string Name { get; set; }
public byte[] File { get; set; }
}
View
@model TEST.Model.Strategy
@using (Html.BeginForm("Add", "Strategy", FormMethod.Post, new { @id = "frmStrategy", enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(x => x.Name)
<input id="templateFile" name="templateFile" type="file" />
@Html.HiddenFor(x => x.ID)
}
控制器
[HttpPost]
public ActionResult Add(Strategy model, HttpPostedFileBase templateFile)
{
if (templateFile != null && templateFile.ContentLength > 0)
{
try
{
var fname = Path.GetFileName(templateFile.FileName);
using (MemoryStream ms = new MemoryStream())
{
templateFile.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
model.File = array;
}
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)