我正在尝试将两个不同的文件上传到同一表单上的两个不同的数据库字段中。
------------------------------------
reportid | name | image | template |
------------------------------------
这是 table 的样子。所以我想将文件上传到图像和模板。我的模型:
public class Report
{
[Key]
public int ReportID { get; set; }
[Required]
public string Name { get; set; }
public byte[] Image { get; set; }
public byte[] Template { get; set; }
}
我在 Controller 中的创建方法:
public ActionResult Create(Report report, HttpPostedFileBase file, HttpPostedFileBase temp)
{
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
report.Image = ms.GetBuffer();
}
}
if (temp != null && temp.ContentLength > 0)
{
using (MemoryStream ms1 = new MemoryStream())
{
temp.InputStream.CopyTo(ms1);
report.Template = ms1.GetBuffer();
}
}
db.Reports.Add(report);
db.SaveChanges();
db.Configuration.ValidateOnSaveEnabled = true;
return RedirectToAction("Index");
}
以及关于上传的部分 View :
<div class="editor-label">
<%:Html.LabelFor(model => model.Image) %>
</div>
<div class="editor-field">
<input type="file" id="fuImage" name="file" />
</div>
<div class="editor-label">
<%:Html.Label("Template") %>
</div>
<div class="editor-field">
<input type="file" id="temp" name="temp"/>
</div>
<p>
<input type="submit" value="Create" />
</p>
因为我无法使用 IEnumerable<HttpPostedFileBase> files
,所以我陷入了困境作为 Create
中的参数方法,因为我需要将它保存在不同的字段中,或者我可以吗?我应该如何处理这个问题?请帮忙:S
注意:图片上传正常。
最佳答案
为什么不使用 IEnumerable<HttpPostedFileBase>
?您可以像这样使用它。
[HttpPost]
public ActionResult Create(Report report, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
//Let's take first file
if(files.ElementAt(0)!=null)
{
var file1=files.ElementAt(0);
if (file1!= null && file1.ContentLength > 0)
{
//do processing of first file
}
}
//Let's take the second one now.
if(files.ElementAt(1)!=null)
{
var temp =files.ElementAt(1);
if (temp!= null && temp.ContentLength > 0)
{
//do processing of second file here
}
}
}
//Do your code for saving the data.
return RedirectToAction("Index");
}
编辑:在您的编辑中看到您的 View 标记之后。
文件输入元素的名称应该与您的操作方法中的参数名称相同。 (本例中为 files
)
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<b>File 1</b>
<input type="file" name="files" id="file1" />
<b>File 2</b>
<input type="file" name="files" id="file2" />
<input type="submit" />
}
此代码假定只读取集合中的前 2 个条目。由于您只需要 2 个文件,因此我对索引进行了硬编码。
Phil 有一个不错的博客 post很好地解释了它。
关于asp.net-mvc - ASP.NET MVC 两个文件上传,不同的目的地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11225636/