无法在MVC中上传文件

时间:2018-10-12 12:20:52

标签: c# .net asp.net-mvc

我在将文件上传到数据库时遇到问题,PostedFile始终为空。

控制器:

public ActionResult Create(Sound sound)
    {
        if (sound.PostedFile != null && sound.PostedFile.ContentLength > 0)
        {
            MemoryStream temp = new MemoryStream();
            sound.PostedFile.InputStream.CopyTo(temp);
            sound.Data = temp.ToArray();
            db.SoundsTable.Add(sound);
            db.SaveChanges();
            ViewBag.Message = "DONE";
        }
        else
        {
            ViewBag.Message = "ERR";
        }
        return RedirectToAction("Index");
    }

型号:

  public class Sounds : DbContext
{
    public Sounds()
        : base("name=Sounds")
    {
    }
    public virtual DbSet<Sound> SoundsTable { get; set; }
}

public class Sound
{
    public int Id { get; set; }
    public string Name { get; set; }
    [MaxLength(8388608)]
    public byte[] Data { get; set; }
    [NotMapped]
    [Required(ErrorMessage = "Please select file.")]
    public HttpPostedFileBase PostedFile { get; set; }

}

查看:

@model WebApp.Models.Sound

@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>

@using (Html.BeginForm())
{
    <div class="form-horizontal">
         <h4>Sound</h4>
         @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })<br />
         @Html.TextBoxFor(model => model.PostedFile, new { type = "file" })<br />
         @Html.ValidationMessageFor(model => model.PostedFile, "", new { @class = "error" })<br />
         <input type="submit" value="UPLOAD" />
         <br />
     @ViewBag.Message
    </div>
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
}

一切正常,将Name值从View发送到Controller时,一切正常。但是我无法发送“ PostedFile”值,因为它始终为空。

2 个答案:

答案 0 :(得分:1)

enctype = multipart/form-data确实是必需的

@using (Html.BeginForm("Create", //Your action
                           "Test", //Your controller
                           FormMethod.Post,
                           new { enctype = "multipart/form-data"}))
{
    <div class="form-horizontal">
        <h4>Sound</h4>
        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })<br />
        @Html.TextBoxFor(model => model.PostedFile, new { type = "file" })<br />
        @Html.ValidationMessageFor(model => model.PostedFile, "", new { @class = "error" })<br />
        <input type="submit" value="UPLOAD" />
        <br />
        @ViewBag.Message
    </div>
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
} 

答案 1 :(得分:0)

尝试一下:

/root/.m2/repository

然后是您的控制器:

@using (Html.BeginForm("Create", "Test", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    //other controls here

    <input type="file" name="postedFile" id="fileInputId" />

    //submit button here }

确保输入文件元素中的名称与控制器中的参数名称相同。