我正在尝试使用Create方法将图像保存到数据库,但是当我尝试运行此代码时,我会遇到以下错误:
输入不是有效的Base-64字符串,因为它包含一个非Base 64字符,超过两个填充字符或一个填充字符中的非空格字符。
我对MVC非常陌生。真的感谢您的回复,提前致以感谢。
[Authorize]
[HttpPost]
public ActionResult Create(Customers saveCustomer)
{
try
{
// TODO: Add insert logic here
var upload = Request.Files["ImageData"];
if (upload.ContentLength > 0)
{
string savedFileName = Path.Combine(
ConfigurationManager.AppSettings["FileUploadDirectory"],
"customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
upload.SaveAs(savedFileName);
}
_db.Customers.InsertOnSubmit(saveCustomer);
_db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
这是我的创建视图代码:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Reservation.Models.Customers>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Create</h2>
<% using (Html.BeginForm("Create", "Customers", FormMethod.Post, new {enctype="multipart/form-data"})) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Add new customer record</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.LastName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LastName) %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Email) %>
<%: Html.ValidationMessageFor(model => model.Email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Phone) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Phone) %>
<%: Html.ValidationMessageFor(model => model.Phone) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.CustomerNote) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.CustomerNote) %>
<%: Html.ValidationMessageFor(model => model.CustomerNote) %>
</div>
<div>
<input type="file" id="ImageData" name="ImageData" />
</div>
<p>
<input type="submit" value="Add recrod" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
Web.config:
<appSettings>
<add key="FileUploadDirectory" value="~/Resources/images/customers/" />
</appSettings>
数据库条目:
Column Name Data Type Allow Nulls
ImageData image yes