使用ASP.NET MVC将图片保存到数据库

5

我正在尝试使用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 

在保存文件之前,您必须将其转换。 - bastianwegge
谢谢您的回复,您能否解释一下我应该在哪里添加这段代码?您能否将以下代码添加到我的示例中,以便我可以清楚地理解? - JAML
你能否将图像写入请求并发布数据? - bastianwegge
我认为这行代码就是做这件事的 _db.Customers.InsertOnSubmit(saveCustomer); 我已经在上面发布了全部的代码,我的代码里没有其他的东西,也许我会遗漏掉了? - JAML
2个回答

1

试试这个:

string savedFileName = Server.MapPath("/Resources/images/customers/" + "customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");

替代

string savedFileName = Path.Combine(
                      ConfigurationManager.AppSettings["FileUploadDirectory"],
                      "customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
  1. 如果您的客户模型包含图像字段,则无需保存到服务器端目录。

  2. 表单提交不应该有上传文件字段,请将控制器更改为:

================================

[Authorize]
[HttpPost]
public ActionResult Create([Bind(Exclude = "ImageData")]Customers saveCustomer, HttpPostedFileBase ImageData)
{
    try
    {
        // TODO: Add insert logic here
        var upload = Request.Files["ImageData"];
        string savedFileName = "";  //string for saving the image server-side path          
        if (upload.ContentLength > 0)
        {
             savedFileName = Server.MapPath("/Resources/images/customers/" + "customer_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg"); //get the server-side path for store image 
            upload.SaveAs(savedFileName); //*save the image to server-side 
        }
        var index = savedFileName.IndexOf(@"\Resources\");            
        saveCustomer.ImageData = savedFileName.Substring(index, savedFileName.Length - index); //set the string of image server-side path to add-object             
        _db.Customers.InsertOnSubmit(saveCustomer); // save all field to databae (includes image server-side path)
        _db.SubmitChanges();  // save database changes
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
} 

是的,我就是这样做的,改变了那一行代码,但是没有成功,你能否请检查一下我的所有代码文件,我是否做对了? - JAML
你能给我提供客户“模型”吗?它包含一个图像字段吗? - Maidot
我正在使用Linq进行此操作,我没有为此创建任何模型,我将客户表拖到我的Reservation.dbml文件中,这一切都是由它完成的。我能够存储所有其他信息,但在添加图像文件后,我遇到了那个错误。 - JAML
现在所有功能都正常了,使用以下代码,但唯一的问题是没有将图像路径保存到数据库中,以便稍后检索。                    string savedFileName = Server.MapPath("/ Resources / images / customers /" +“customer_”+ saveCustomer.FirstName +“_”+ saveCustomer.LastName +“.jpg”);                     upload.SaveAs(savedFileName); - JAML
我认为我发布的最终答案很好:),如果您有问题,请告诉我~ - Maidot
显示剩余21条评论

0
private byte[] ImageToBytes(Image img, ImageFormat format)
{            
 MemoryStream mstream = new MemoryStream();
 img.Save(mstream, format);
 mstream.Flush();
 return mstream.ToArray();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接