WeakTaenie
WeakTaenie

Reputation: 247

Error Occurs When Store File into Database

An error occurs When I try To upload File The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. My Assignment DB attribute >> FileLocation is a varBinary(MAX) , which part did i do wrong?

Controller

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

View

    <% 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>

......

Model

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

Upvotes: 0

Views: 652

Answers (1)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18883

Instead of

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

take simple html tag as :

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

this will work fine..

Upvotes: 1

Related Questions