将文件存储到数据库时出错

时间:2014-08-06 15:01:37

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

当我尝试上传文件时发生错误 输入不是有效的Base-64字符串,因为它包含非基本64个字符,两个以上的填充字符或填充字符中的非法字符。 我的作业数据库属性>> FileLocation是一个varBinary(MAX), 哪部分我做错了?

控制器

[HttpPost]
    public ActionResult Create(Assignment assignment)
    {
        if (Request.Files != null && Request.Files.Count == 1)
        {
            var file = Request.Files[0];
            if (file != null && file.ContentLength > 0)
            {
                var content = new byte[file.ContentLength];
                file.InputStream.Read(content, 0, file.ContentLength);
                assignment.FileLocation = content;
                // the rest of your db code here
            }

        }
        assignment.SubmissionDate = DateTime.Now;
        db.Assignments.Add(assignment);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

查看

    <% using (Html.BeginForm("Create", "Assignment", FormMethod.Post, new { enctype = "multipart/form-data" }))
   { %>
    <%: Html.ValidationSummary(true) %>

...........

    <div class="editor-label">
        <%: Html.LabelFor(model => model.FileLocation) %>
    </div>
    <div class="editor-field">
       <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
    <%: Html.ValidationMessageFor(model => model.FileLocation) %>
    </div>

......

模型

public string AssignmentID { get; set; }
    public Nullable<System.DateTime> SubmissionDate { get; set; }
    public string Status { get; set; }
    //[Range(0,100, ErrorMessage="Only Value between 0-100 is accepted.")]
    public Nullable<decimal> Mark { get; set; }
    public string Comments { get; set; }
    public byte[] FileLocation { get; set; }

1 个答案:

答案 0 :(得分:1)

而不是

<%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>

将简单的html标记用作:

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

这样可以正常工作..