ASP.NET MVC文件上载错误 - “输入不是有效的Base-64字符串”

时间:2021-11-09 18:31:12

I'm trying to add a file upload control to my ASP.NET MVC 2 form but after I select a jpg and click Save, it gives the following error:

我正在尝试将文件上传控件添加到我的ASP.NET MVC 2表单中,但在我选择jpg并单击“保存”后,它会出现以下错误:

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.

输入不是有效的Base-64字符串,因为它包含非基本64个字符,两个以上的填充字符或填充字符中的非空白字符。

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

谢谢,贾斯汀

4 个解决方案

#1


6  

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.

我刚刚尝试了您的代码,并且能够上传而没有任何问题。我没有保存到数据库,我的Developer类也没有Photo属性。

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>

#2


16  

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

我最近找到了一个解决方案,虽然我现在使用MVC3而不是MVC2。

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

在“保存”操作中,从绑定对象中排除二进制字段,并包含单独的HttpPostedFileBase字段:

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.:

请注意,您也可以这样做,以避免必须包含View中的Html.Hidden元素。例如。:

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.

然后,您可以直接使用此HttpPostedFileBase对象,而不是需要访问Request.Files。

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

就个人而言,我实际上使用以下代码将这些类型的图像存储在SQL“图像”字段的数据库中:

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

标记

#3


1  

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.

我刚从控制器的电话中排除了Logo。

#4


0  

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:

我有同样的错误,但上面的解决方案对我不起作用,而是我注意到我的Model属性名称与我传递给控制器​​的参数名称相同:

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

My Model property name is

我的Model属性名称是

public byte[] Upload { get; set; }

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

在使用不同的参数名称重命名后,它现在可以正常工作:

public ActionResult EditSOP(File file, HttpPostedFileBase UploadFile)

#1


6  

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.

我刚刚尝试了您的代码,并且能够上传而没有任何问题。我没有保存到数据库,我的Developer类也没有Photo属性。

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>

#2


16  

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

我最近找到了一个解决方案,虽然我现在使用MVC3而不是MVC2。

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

在“保存”操作中,从绑定对象中排除二进制字段,并包含单独的HttpPostedFileBase字段:

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.:

请注意,您也可以这样做,以避免必须包含View中的Html.Hidden元素。例如。:

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.

然后,您可以直接使用此HttpPostedFileBase对象,而不是需要访问Request.Files。

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

就个人而言,我实际上使用以下代码将这些类型的图像存储在SQL“图像”字段的数据库中:

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

标记

#3


1  

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.

我刚从控制器的电话中排除了Logo。

#4


0  

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:

我有同样的错误,但上面的解决方案对我不起作用,而是我注意到我的Model属性名称与我传递给控制器​​的参数名称相同:

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

My Model property name is

我的Model属性名称是

public byte[] Upload { get; set; }

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

在使用不同的参数名称重命名后,它现在可以正常工作:

public ActionResult EditSOP(File file, HttpPostedFileBase UploadFile)