2

我正在尝试将两个不同的文件上传到同一表单上的两个不同的数据库字段中。

------------------------------------
reportid | name | image | template |
------------------------------------

这是表格外观。所以我想将文件上传到图像和模板。我的模型:

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; }

}

我在控制器中的 Create 方法:

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");  
        }

关于上传的部分观点:

<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

注意:图片上传工作正常。

4

1 回答 1

6

为什么不使用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");
}

编辑:在您的编辑中看到您的视图标记后。

文件输入元素的名称应与您的操作方法中的参数名称相同。(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 有一篇很好的博客文章很好地解释了它。

于 2012-06-27T12:12:01.227 回答