开发者

ASP.NET MVC File Upload Error - "The input is not a valid Base-64 string"

I'm trying to add a file upload con开发者_JS百科trol to my ASP.NET MVC 2 form but after I select a jpg and click Save, it gives the following error:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.

Here's the view:

<% using (Html.BeginForm("Save", "Developers", FormMethod.Post, new {enctype = "multipart/form-data"})) { %>
    <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>Fields</legend>

        <div class="editor-label">
            Login Name
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.LoginName) %>
            <%: Html.ValidationMessageFor(model => model.LoginName) %>
        </div>

        <div class="editor-label">
            Password
        </div>
        <div class="editor-field">
            <%: Html.Password("Password") %>
            <%: Html.ValidationMessageFor(model => model.Password) %>
        </div>

        <div class="editor-label">
            First Name
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.FirstName) %>
            <%: Html.ValidationMessageFor(model => model.FirstName) %>
        </div>

        <div class="editor-label">
            Last Name
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.LastName) %>
            <%: Html.ValidationMessageFor(model => model.LastName) %>
        </div>

        <div class="editor-label">
            Photo
        </div>
        <div class="editor-field">
            <input id="Photo" name="Photo" type="file" />
        </div>

        <p>
            <%: Html.Hidden("DeveloperID") %>
            <%: Html.Hidden("CreateDate") %>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
<% } %>

And the controller:

//POST: /Secure/Developers/Save/
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(Developer developer)
        {
            //get profile photo.
            var upload = Request.Files["Photo"];
            if (upload.ContentLength > 0)
            {
                string savedFileName = Path.Combine(
                      ConfigurationManager.AppSettings["FileUploadDirectory"],
                      "Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg");
                upload.SaveAs(savedFileName);
            }
            developer.UpdateDate = DateTime.Now;
            if (developer.DeveloperID == 0)
            {//inserting new developer.
                DataContext.DeveloperData.Insert(developer);
            }
            else
            {//attaching existing developer.
                DataContext.DeveloperData.Attach(developer);
            }
            //save changes.
            DataContext.SaveChanges();
            //redirect to developer list.
            return RedirectToAction("Index");
        }

Thanks, Justin


I have recently found a solution for this, although I am now using MVC3 rather than MVC2.

In the Save action, exclude the binary field from the bound object and include a separate HttpPostedFileBase field:

e.g.

public ActionResult Save([Bind(Exclude = "Photo")]Developer developer, HttpPostedFileBase Photo) {...}

Note that you can also do this to avoid having to include the Html.Hidden elements from your View. e.g.:

public ActionResult Save([Bind(Exclude = "Photo,DeveloperID,CreateDate")]Developer developer, HttpPostedFileBase Photo) {...}

You can then use this HttpPostedFileBase object directly rather than needing to access Request.Files.

Personally, I actually store these types of images in the database in an SQL "image" field using this code:

if (Picture != null)
{
    if (Picture.ContentLength > 0)
    {
        byte[] imgBinaryData = new byte[Picture.ContentLength];
        int readresult = Picture.InputStream.Read(imgBinaryData, 0, Picture.ContentLength);
        Developer.Picture = imgBinaryData;
    }
}

Hope this is helpful...

Mark


I just tried your code and was able to upload without any issues. I did not save to the database nor does my Developer class have a Photo property.

namespace MvcApplication5.Controllers
{
    public class Developer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime UpdateDate { get; set; }
        public int DeveloperID { get; set; }
        public string LoginName { get; set; }
        public string Password { get; set; }
    }
}

Controller

public class DefaultController : Controller
{
    //
    // GET: /Default/

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Index()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(Developer developer)
    {
        //get profile photo. 
        var upload = Request.Files["Photo"];
        if (upload.ContentLength > 0)
        {
            string savedFileName = Path.Combine(
                  @"C:\temp",
                  "Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg");
            upload.SaveAs(savedFileName);
        }
        developer.UpdateDate = DateTime.Now;
        if (developer.DeveloperID == 0)
        {//inserting new developer. 

        }
        else
        {//attaching existing developer. 

        }
        //save changes. 

        //redirect to developer list. 
        return RedirectToAction("Index");
    }

}

View

<div>
        <% using (Html.BeginForm("Save", "Default", FormMethod.Post, new { enctype = "multipart/form-data" }))
           { %>
        <%: Html.ValidationSummary(true)%>
        <fieldset>
            <legend>Fields</legend>
            <div class="editor-label">
                Login Name
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.LoginName)%>
                <%: Html.ValidationMessageFor(model => model.LoginName)%>
            </div>
            <div class="editor-label">
                Password
            </div>
            <div class="editor-field">
                <%: Html.Password("Password")%>
                <%: Html.ValidationMessageFor(model => model.Password)%>
            </div>
            <div class="editor-label">
                First Name
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.FirstName)%>
                <%: Html.ValidationMessageFor(model => model.FirstName)%>
            </div>
            <div class="editor-label">
                Last Name
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.LastName)%>
                <%: Html.ValidationMessageFor(model => model.LastName)%>
            </div>
            <div class="editor-label">
                Photo
            </div>
            <div class="editor-field">
                <input id="Photo" name="Photo" type="file" />
            </div>
            <p>
                <%: Html.Hidden("DeveloperID")%>
                <%: Html.Hidden("CreateDate")%>
                <input type="submit" value="Save" />
            </p>
        </fieldset>
        <%} %>
    </div>


I got the same issue. here is the solution I found. Class property:

public byte[] Logo { get; set; }

View Code:

@using (Html.BeginForm("StoreMyCompany", "MyCompany", FormMethod.Post, new { id = "formMyCompany", enctype = "multipart/form-data" }))
{
 <div class="form-group">
  @Html.LabelFor(model => model.modelMyCompany.Logo, htmlAttributes: new { @class = "control-label col-md-3" })
    <div class="col-md-6">
    <input type="file" name="Logo" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
    </div>
 </div>
 }

Controller Code:

 public ActionResult StoreMyCompany([Bind(Exclude = "Logo")]MyCompanyVM model)
    {
        try
        {
            Company objCompany = new Company();

            byte[] imageData = null;
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase objFiles = Request.Files["Logo"];

                using (var binaryReader = new BinaryReader(objFiles.InputStream))
                {
                    imageData = binaryReader.ReadBytes(objFiles.ContentLength);
                }
            }
        }
        catch (Exception ex)
        {
            Utility.LogError(ex);
        }

        return View();
    }
}

i just excluded Logo from controller's call.


I have the same error, but the solution above didn't work for me, instead I notice that my Model property name is the same as the parameter name I am passing with the controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditSOP(File file, HttpPostedFileBase Upload)

My Model property name is

public byte[] Upload { get; set; }

After renaming it on a different parameter name, it now works:

public ActionResult EditSOP(File file, HttpPostedFileBase UploadFile)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜